javascriptjqueryhtmlforms

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


Solution

  • Add the onsubmit attribute to the form tag:

    <form name="search" onsubmit="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;
    }