Skip to content
Advertisement

How to handle form submitted with JQuery

I have a multistep form. I’m validating each step with Javascript before submitting it to PHP.

If the form’s last step passes validation tests. I’m submitting the form. like so

$(UISelectors.addListForm)[0].submit();

I want to handle form submission with Javascript and submit it to PHP with Ajax. but instead, the page refreshes.

const addListingSubmit = (e) => {
  e.preventDefault();

 // ...
};

$(UISelectors.addListForm).submit(addListingSubmit);

Any suggestions?

Here is my code: https://jsfiddle.net/cd1mkuge/1/

Advertisement

Answer

An HTML form natively calls a defined url (for which the code is missing in your question) when it is submitted, and thus will leave the current page. To avoid this behaviour use a click handler (on the form’s submit button) instead, and do your ajax call in there with the form’s values:

const onClick = e => {
    // get values from the form
    const foo = $("#foo-field").val();
    // etc.

    // do AJAX call
    $.post(...)
};

$('#my-button').click(onClick);

This way, the form’s submit event is never triggered.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement