Skip to content Skip to sidebar Skip to footer

Can I Use The Submit Button To Activate An AJAX Function?

I have an HTML form that currently just posts the data directly to a PHP file. I want to update the code so that the submit button sends the data to a JavaScript function so that

Solution 1:

You can give the "submit" input a "click" handler that explicitly prevents the default behavior from being carried out.

<input type='submit' value='Submit' onclick='ajax(event)'>

Then in the function:

function ajax(event) {
  if ('preventDefault' in event) event.preventDefault();
  event.returnValue = false; // for IE before IE9
  // ...
}

edit @Esailija points out correctly that another option is to handle the "submit" event on the <form> element instead. The function would look pretty much the same, in fact exactly the same, but you'd wire it up like this:

<form id='yourForm' onsubmit='ajax(event)'>

That will also trap things like the "Enter" key action, etc.


Solution 2:

Of course you can. But it's more useful to call your Javascript function in the input like this :

 <input type="submit" value="Submit" onclick="ajax();" />

And remove the action part in the form.


Solution 3:

I jQuery you can use event.preventDefault(); otherwise just use return false;

http://jsfiddle.net/mKQmR/

http://jsfiddle.net/mKQmR/1/


Solution 4:

Pointy is correct... just add a click handler to the submit button, however make sure the last line of the click handler returns "false" to prevent the form from actually being posted to the form's action.

<html>
<head>
<script type="text/javascript">
function ajax(){
  //...
return false;
}
</script>
</head>

<body>
<form action="thispage.htm">
  <!-- ... -->
  <input type="submit" value="Submit" onclick="ajax();" />
</form>
</body>
</html>

Post a Comment for "Can I Use The Submit Button To Activate An AJAX Function?"