It is always great when you can allow users to send data from your forms via ajax. The user does not need to leave the page and if the data has been successfully transferred he/she is provided with success message.
This piece of code should placed into your javascript function after the successful validation which means it should only be executed if the content of the form elements passes the validation.
There is couple of ways how you can implement ajax to your form with jQuery. This is one of them.
// lets define which form are we going to use, so the data could be serialized
dataString = $("#footer_contact_form").serialize();
$.ajax({
type: "POST",
global: false,
url: $url, // you would usually pass the url as a variable into the function which includes this ajax section - e.g. ajax_form($url) but you could also specify the url directly in this place
data: dataString,
// here we will specify what will happen after the data is sent
success: function() {
if($('.success_message').length == 0){
$('<p class="success_message">Thank you for your message!</p>').insertBefore('#submit_cover'); // insert the success message into the DOM and hide it
$('.success_message').hide();
// Clear the form
$('#footer_contact_form input').val(""); // clean the form default values so the user gets the feeling that they were sent away
$('#footer_contact_form textarea').val("");
$('.success_message').fadeIn(1000); // fades in the success message which we have inserted before but hided
}else{
$('.success_message').show(); // as you can see on top we have condition which check if the success message is already in place so we do not insert it more then once. If it is already in the DOM we just show it.
}
}
});
There are so many ways how you can do this. You could also add condition which will cover the case when the form is not sent, lets say there are internet connection problems. Do not forget to validate the code first before using the ajax function.