Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML: JavaScript: Block Form submission and call Javascript function

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

like image 408
Sridhar Avatar asked Jan 23 '13 04:01

Sridhar


People also ask

How do you call a function when a form is submitted?

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.

How do I stop HTML form from submitting?

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.

How does JavaScript prevent a form from being submitted?

Use the return value of the function to stop the execution of a form in JavaScript.


2 Answers

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; } 
like image 169
Miqdad Ali Avatar answered Sep 23 '22 17:09

Miqdad Ali


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.

like image 37
Explosion Pills Avatar answered Sep 22 '22 17:09

Explosion Pills