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

前端 未结 3 1419
半阙折子戏
半阙折子戏 2020-12-15 11:17

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 havi

3条回答
  •  [愿得一人]
    2020-12-15 12:04

    $("#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('
    Well done! You successfully read this important alert message.
    '); }); // 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); }); } });

提交回复
热议问题