How to continue form submission after an AJAX call?

后端 未结 4 373
陌清茗
陌清茗 2021-01-14 11:08

I want to validate user entries on a WordPress post upon hitting the submit button, display an error message is there are problems, and submit the form if everything is OK.

4条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-14 11:50

    Short answer: You can't - not in this manner.

    Some background: The callbacks you supply as arguments to functions such as $.post are executed asynchronously. This means that you will return proceed before your success callback has been executed, and proceed will always be false. With your breakpoint, if you wait until the success callback has executed, proceed will be true and all will be well.

    So, if you want to submit the form after your ajax request has finished, you must submit it using javascript. This is pretty easy with jQuery, just do a jQuery $.post with data: $("yourForm").serialize() and url: yourForm.action.

    This is basically what you already are doing, you just have to repeat that call to the URL to which you actually want to post the data.

    EDIT:

    Another way would be to set an attribute on your form, say valid, and in your submit handler check that:

    jQuery("#post").submit(function() {
        if($(this).data("valid")) {
            return true;
        }
        // Rest of your code
    });
    

    And in the success callback for your validation ajax request you would set/clear that attribute, and then submit:

    $("#post").data("valid", true).submit();
    

    EDIT:

    You also want to do your "ajax-loading"/button enabling inside the callback for $.post for the same reasons stated above - as it is, they will happen immediately, before your ajax call returns.

提交回复
热议问题