Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery validate with AJAX in submitHandler, submits on second click?

I'm new to AJAX and used the code from this SO answer here jQuery Ajax POST example with PHP to integrate with a form on a WordPress site. It works just fine, but i'm having trouble integrating it with jquery validation

I tried placing the javascript from the page above into the submitHandler function below

$("#my-form").validate({
  submitHandler: function(form) {
    **js from other page**
  }
});

My form validates on the first click. Then if i type into the input and submit nothing happens, I have to click a second time for the form to submit properly with AJAX. Below is a jsfiddle. Any help is appreciated thanks.

A jsfiddle of my code thought it'll log an error to console since form.php isn't linked

like image 553
Anagio Avatar asked Aug 16 '13 04:08

Anagio


3 Answers

The job of the submitHandler is to submit the form, not to register a form submit event handler.

The submitHandler is called when the formm submit event is triggered, in your case instead of submitting the form you were registering a submit handler so when the form submit event is triggered for the first time the form is not submitted. when it is fired for the second time first the submit event is processed by the validator then the handler you registered is fired which triggers the ajax request.

In the submitHandler you just have to sent the ajax request there is no need to register the event handler

$("#add-form").validate({
    submitHandler: function (form) {
        // setup some local variables
        var $form = $(form);
        // let's select and cache all the fields
        var $inputs = $form.find("input, select, button, textarea");
        // serialize the data in the form
        var serializedData = $form.serialize();

        // let's disable the inputs for the duration of the ajax request
        $inputs.prop("disabled", true);

        // fire off the request to /form.php

        request = $.ajax({
            url: "forms.php",
            type: "post",
            data: serializedData
        });

        // callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR) {
            // log a message to the console
            console.log("Hooray, it worked!");
            alert("success awesome");
            $('#add--response').html('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button><strong>Well done!</strong> You successfully read this important alert message.</div>');
        });

        // callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown) {
            // log the error to the console
            console.error(
                "The following error occured: " + textStatus, errorThrown);
        });

        // callback handler that will be called regardless
        // if the request failed or succeeded
        request.always(function () {
            // reenable the inputs
            $inputs.prop("disabled", false);
        });

    }
});
like image 194
Arun P Johny Avatar answered Nov 14 '22 20:11

Arun P Johny


Calling $("#add-form").submit(function(){...}) doesn't submit the form. It binds a handler that says what to do when the user submits the form. That's why you have to submit twice: the first time invokes the validate plugin's submit handler, which validates the data and runs your function, and the second time invokes the submit handler that you added the first time.

Don't wrap the code inside .submit(), just do it directly in your submitHandler: function. Change:

var $form = $(this);

to:

var $form = $(form);

You don't need event.PreventDefault(), the validate plugin does that for you as well.

like image 27
Barmar Avatar answered Nov 14 '22 20:11

Barmar


$("#add-form").validate({
    submitHandler: function (form) {
        var request;
        // bind to the submit event of our form



        // let's select and cache all the fields
        var $inputs = $(form).find("input, select, button, textarea");
        // serialize the data in the form
        var serializedData = $(form).serialize();

        // let's disable the inputs for the duration of the ajax request
        $inputs.prop("disabled", true);

        // fire off the request to /form.php

        request = $.ajax({
                url: "forms.php",
                type: "post",
                data: serializedData
        });

        // callback handler that will be called on success
        request.done(function (response, textStatus, jqXHR) {
                // log a message to the console
                console.log("Hooray, it worked!");
                alert("success awesome");
                $('#add--response').html('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">×</button><strong>Well done!</strong> You successfully read this important alert message.</div>');
        });

        // callback handler that will be called on failure
        request.fail(function (jqXHR, textStatus, errorThrown) {
                // log the error to the console
                console.error(
                    "The following error occured: " + textStatus, errorThrown);
        });

            // callback handler that will be called regardless
            // if the request failed or succeeded
        request.always(function () {
                // reenable the inputs
                $inputs.prop("disabled", false);
        });            

    }
});
like image 2
suhailvs Avatar answered Nov 14 '22 20:11

suhailvs