Button submission through Ajax using Javascript

The solution to making a button do an AJAX call in jQuery can be achieved by following these steps:
1. In the success function, disable the button and change its color.
2. If you’re experiencing a two-click issue, handle the button change in the submitting function or in the event function rather than only when the event has occurred.


Solution 1:

Consider decoupling the form submission from the validation process.

Simply changing this line:

$("form").submit(function(e) {

to

$("input[name='register']").click(function(e) {


Solution 2:


Initially, I suggest utilizing a success function instead of a .done() function for the sake of clarity. As an instance:

$("form").submit(function(e) {
    e.preventDefault();
    var $form = $(this);
    var serializedData = $form.serialize();
    request = $.ajax({
        // Merge the check.php and register.php into one file so you don't have to  'send' the data twice.
        url: "register.php",
        type: "post",
        data: { formData: serializedData },
        datetype: "JSON",
        success: function() {
            console.log("This form has been submitted via AJAX");
        }
    });
});

I have omitted the .unbind() function, which may be the cause of your code’s malfunction. This function deletes the event handlers from the form, irrespective of their type (refer: http://api.jquery.com/unbind/). Additionally, I have placed the e.preventDefault() at the beginning. I recommend that you test this revised code and inform us whether or not it works.

Additionally, it’s not necessary to submit the data when transmitting it through AJAX.


Solution 3:

Try this one.

$("form").submit(function(e) {
    var $form = $(this);
    var serializedData = $form.serialize();    
    request = $.ajax({
        url: "check.php",
        type: "post",
        data: { formData: serializedData },
        datetype: "JSON"
    });
    request.done(function(response, textStatus, jqXHR) {
        console.log("HELLO");
        $('form').unbind(); 
        $('form').submit();
    });
});

Frequently Asked Questions