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
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 yoursubmitHandler:
function. Change:to:
You don't need
event.PreventDefault()
, the validate plugin does that for you as well.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