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.

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

Then in the function:

function ajax(event) {
  if ('preventDefault'inevent) 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 :

 <inputtype="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><scripttype="text/javascript">functionajax(){
  //...returnfalse;
}
</script></head><body><formaction="thispage.htm"><!-- ... --><inputtype="submit"value="Submit"onclick="ajax();" /></form></body></html>

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