I want to make AJAX call when a submit button in the form pressed. InFact I cant remove the <form>
because I want to made clientside validation also. I tried this code.
<form name="search" > Name: <input type="text" name="name1"/> Age: <input type="text" name="age1"/> <input type="submit" name="Submit" value="Submit" onclick="makeSearch()"/> </form>
JS
function makeSearch(){ alert("Code to make AJAX Call"); }
After using this code alert() not showing but the page is reloaded. I want to block the page reload and call the JS function.
Thanks
You can put your form validation against this event type. The following example shows how to use onsubmit. Here we are calling a validate() function before submitting a form data to the webserver. If validate() function returns true, the form will be submitted, otherwise it will not submit the data.
The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmit property in the HTML <form> element.
Use the return value of the function to stop the execution of a form in JavaScript.
Add the onsubmit
attribute to the form
tag:
<form name="search" onsubmit="return makeSearch()" > Name: <input type="text" name="name1"/> Age: <input type="text" name="age1"/> <input type="submit" name="Submit" value="Submit"/> </form>
And javascript add return false
at the end:
function makeSearch() { alert("Code to make AJAX Call"); return false; }
The correct, jQuery way would be:
$("form").on('submit', function (e) { //ajax call here //stop form submission e.preventDefault(); });
Like you said, you could also remove the <form>
element and just bind the ajax call to the button's click
event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With