javascript: make a POST call on button click

I want to make a POST on button click by adding an event listener to it, but with ajax I can make the call but I do not have any data or success, error criteria for the same.

one way I found was using form submit event, but I guess it is not the right way to do it, I should be making a POST call on button click.

<div id="googleSignInDiv" class="cols-row ">
   <form id="googleSignInform" action="/connect/google" method="post"
      <button type="submit" class="btn-primary btn-sub-action  gss-col-12 type-300 social-button google" 
         id="signin-login-google-button" >
      <span class="icon social-icon"></span>
      <span class="btn-label">

If I do something like this in my onclick function, its not working as desired, neither am getting any error.

    url: '/connect/google',
    type: 'POST'

And after this, I have my code to open the new window. How can I make a post call and mark its target as the google-auth-window which I have defined in my code? or using the form is the correct way?



The default behaviour of a button of type submit in a form is to submit it, so you have to prevent the default behaviour first by using event.preventDefault() and followed by what you desire to do on click of the button (ex: validations etc.). In your case you can call the function that makes the AJAX call (makeAjaxRequest). Your code will look something like this:

function makeAjaxRequest() {
      url: '/connect/google',
      type: 'POST',
      success: function(data){
        //code to open in new window comes here

On success of the ajax call you can write code to open it in a new window. You can refer to this answer for the same.


I guess your problem is not about how to handle Ajax calls, rather how to integrate google user login with user and not doing by submitting the form but should be done async. (Correct me I am wrong :) )

I think the if you follow google documentation here, you might see that google already provides a library in (platform.js) for handling it via ajax and also opens it in a seperate form.

With it you can have a google login button with only

<div class="g-signin2" data-onsuccess="onSignIn"></div>

and it opens a window for login and return backs to your callback url provided in you configuration on Google APIs.

Let me know if you get stuck anywhere. :)


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.