DEV Community

Discussion on: PHP HTML FORM ON SUBMIT DOES NOT PERFORM THE JAVASCRIPT ACTIONS FOR VALIDATION

Collapse
 
tiguchi profile image
Thomas Werner

What you are observing is the default behavior of the HTML form element, which existed before the introduction of JavaScript. The form element has an action attribute, which is the URL to be loaded (with the form data) when the form is submitted. The form is submitted when you click the submit button of the form, or when you hit enter in any form input element. By default that action URL is the current page's URL, that's why you get to see a page reload.

By the sound of it, you want to utilize JavaScript instead for placing a backend request for submitting the data. For that you need to register an onSubmit event listener on the form element, that prevents the default behavior. That can be done by calling the form submit event object's preventDefault method. See also: stackoverflow.com/questions/866448...

One more suggestion. You could or should also use HTML5 form validation features in situations where validation is not overly complicated. That does not require any JS, and it will prevent the form from being submitted if data is missing or malformed.

It is also possible to combine HTML5 form validation with JavaScript validation. You can mark a form element as invalid using JavaScript.

developer.mozilla.org/en-US/docs/L...