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

前端 未结 3 1450
半阙折子戏
半阙折子戏 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:00

    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.

提交回复
热议问题