You can attach the .submit
event to all forms to catch the submission, then use .preventDefault()
on the event object to prevent actual page submission (stop it from changing page). Then serialize the form's data (make a name-value paired string), get the url from the action attribute of the form element and then call jquery's ajax function
using $("form")
with nothing else as part of the selector will attach this to all forms on the page
HTML
<form method='post' action='form_target.php'>
<input type='text' name='fieldname' />
<button type='submit'/>
</form>
JAVASCRIPT
$("form").submit(function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
$.ajax({
url:url,
type:"POST",
data:data,
success:function(){
//do something when post succedes
},
error:function() {
// do something when it fails
}
});
});
<kbd>JQuery .ajax</kbd>
<kbd>JQuery .serialize</kbd>
<kbd>JQuery .submit</kbd>
To further extend this you could make it so each form executes a specific success method, this would help in the case that you need something specific to happen for a specific form submission.
First give each form a data-* attribute that we can later use in the submit event to trigger a specific function for that form.
<form method='post' action='form_target.php'
data-onerror="nameSubmitError"
data-onsuccess="nameSubmitSuccess">
Then create the two functions that we named in the data-* attributes
function nameSubmitError() {
//Do some code that will handle the error
}
function nameSubmitSuccess() {
//Do some code that will handle the success
}
And in the .submit event
$("form").submit(function(e){
e.preventDefault();
var data = $(this).serialize();
var url = $(this).attr("action");
var errorCallback = $(this).data("onerror");
var successCallback = $(this).data("onsuccess");
$.ajax({
url:url,
type:"POST",
success:function(){
//Check that we have a defined function before trying to execute it
if( typeof(window[successCallback]) == "function" ) {
//We do have a defined function so execute it
window[successCallback]();
}
},
error:function() {
//Check that we have a defined function before trying to execute it
if( typeof(window[errorCallback]) == "function" ) {
//We do have a defined function so execute it
window[errorCallback]();
}
}
});
});
Of course putting all the callback functions in the global space would pollute it so you could setup all the functions into a single object and use the objects name instead of window
var formCallbacks = {
nameSubmitError:function() {
//Do some code that will handle the error
},
nameSubmitSuccess: function() {
//Do some code that will handle the success
}
};
And in the .submit event change window
to formCallbacks
//window[errorCallback]();
//Becomes
formCallbacks[errorCallback]();