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 I can create an AJAX function. Is it possible for the submit button to activate a JavaScript function rather than posting to a php file? The only thing I have come up with is below, which quite obviously does not work:
<html>
<head>
<script type="text/javascript">
function ajax(){
//...
}
</script>
</head>
<body>
<form action="ajax();">
<!-- ... -->
<input type="submit" value="Submit" />
</form>
</body>
</html>
Of course you can. But it's more useful to call your Javascript function in the input like this :
And remove the action part in the form.
I jQuery you can use
event.preventDefault();
otherwise just usereturn false;
http://jsfiddle.net/mKQmR/
http://jsfiddle.net/mKQmR/1/
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.
You can give the "submit" input a "click" handler that explicitly prevents the default behavior from being carried out.
Then in the function:
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:That will also trap things like the "Enter" key action, etc.