For a version of this using ColdFusion, see the CF jquery form submit post.
Two jQuery functions that allow for the submission of form are the jQuery.ajax function and the jQuery.post function (there is also jQuery.get but that is not addressed here).
More functionality, along with more complexity, is offered with the .ajax function while the .post function, with its more simple functionality and implementation, will be all that is needed for simple form posts.
It is highly recommended that you get a tool like Firebug to see the post response coming back from the page. It helps immensely.
Here is an example of both in action doing the same thing: form submit with email validation.
jQuery.ajax
The form:
<form id="JqAjaxForm"> <fieldset> <legend>jQuery.ajax Form Submit</legend> <p><label for="name_ajax">Name:</label><br /> <input id="name_ajax" type="text" name="name_ajax" /></p> <p><label for="email_ajax">E-mail:</label><br /> <input id="email_ajax" type="text" name="email_ajax" /></p> <p><input type="submit" value="Submit" /></p> </fieldset> </form> <div id="message_ajax"></div>
Pretty simple, nothing fancy. There is a form for each jQuery function, .ajax and .post. The only difference in the forms are the element names.
jQuery controls the submit for the forms. For the .ajax submission the jQuery is this:
$(function(){
$("#JqAjaxForm").submit(function(e){
e.preventDefault();
dataString = $("#JqAjaxForm").serialize();
$.ajax({
type: "POST",
url: "process_form.php",
data: dataString,
dataType: "json",
success: function(data) {
if(data.email_check == "invalid"){
$("#message_ajax").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_ajax").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
}
}
});
});
});
The .serialize function is used to put the form data in a format that can be processed by a page on the server. The .ajax function options include:
- type: “get” or “post”
- url: the page to receive the form data
- data: the form data itself
- dataType: the data type the function should expect back from the server
- success function: runs on a succesful post to the page
More information on the options and further explanations of the options used here can be found on the jQuery.ajax documentation page.
jQuery.post
As in the .ajax example, the form is simple, only the names have been changed:
<form id="JqPostForm"> <fieldset> <legend>jQuery.post Form Submit</legend> <p><label for="name_post">Name:</label><br /> <input id="name_post" type="text" name="name_post" /></p> <p><label for="email_post">E-mail:</label><br /> <input id="email_post" type="text" name="email_post" /></p> <p><input type="submit" value="Submit" /></p> </fieldset> </form> <div id="message_post"></div>
And again, jQuery controls the submit for the forms. For the .post submission the jQuery is this:
$(function(){
$("#JqPostForm").submit(function(e){
e.preventDefault();
$.post("process_form.php", $("#JqPostForm").serialize(),
function(data){
if(data.email_check == 'invalid'){
$("#message_post").html("<div class='errorMessage'>Sorry " + data.name + ", " + data.email + " is NOT a valid e-mail address. Try again.</div>");
} else {
$("#message_post").html("<div class='successMessage'>" + data.email + " is a valid e-mail address. Thank you, " + data.name + ".</div>");
}
}, "json");
});
});
jQuery.post is a shorter, easier way to post the form data. The function arguments are:
- url of the form processing page
- the form data
- the callback function
- the data type of the return data
More information can be found on the jQuery.post documentation page.
Processing the Form
Both methods are processed by the same page. It processes the form data, process_form.php in this example, by checking to see if the e-mail submitted is valid. Much more than that could be done on the page if needed.
$email_check = '';
$return_json = '';
function isValidEmail($email){
return eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email);
}
if(isValidEmail($_POST['email_ajax']) || isValidEmail($_POST['email_post'])) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_json = '{"email_check":"' . $email_check . '",';
if (isset($_POST['email_ajax'])){
$return_json = $return_json . '"name":"' . $_POST['name_ajax'] . '",';
$return_json = $return_json . '"email":"' . $_POST['email_ajax'] . '"}';
} else {
$return_json = $return_json . '"name":"' . $_POST['name_post'] . '",';
$return_json = $return_json . '"email":"' . $_POST['email_post'] . '"}';
}
echo $return_json;
This code puts the results of the e-mail validation and the form data in a JSON-formatted string. It then will echo the return data string which is picked up by the success function in the .ajax function or the function(data) function in the .post function on the original page.
I prefer working with JSON, but there are other options for the return data. Check the jQuery documentation for the types available to you.
The JSON response will look like this:
{"email_check":"valid","name":"Julia","email":"julia@example.com"}
NOTE: If you have PHP 5.2 or better and the filter_var and json_encode functions available, use the following code instead:
$email_check = '';
$return_arr = array();
if(filter_var($_POST['email_ajax'], FILTER_VALIDATE_EMAIL) || filter_var($_POST['email_post'], FILTER_VALIDATE_EMAIL)) {
$email_check = 'valid';
}
else {
$email_check = 'invalid';
}
$return_arr["email_check"] = $email_check;
if (isset($_POST['email_ajax'])){
$return_arr["name"] = $_POST['name_ajax'];
$return_arr["email"] = $_POST['email_ajax'];
} else {
$return_arr["name"] = $_POST['name_post'];
$return_arr["email"] = $_POST['email_post'];
}
echo json_encode($return_arr);
The appropriate message based on the e-mail validation check is then displayed.
Pretty simple, pretty handy couple of jQuery functions. Once you see it in action, you get the idea.
Usual recommended jQuery and PHP reading:
If this post helped you out, please consider donating to help pay the hosting fees. 100% of the donations go to the web host.
Further Reading:
- jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion
- Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties
- Using jQuery Autocomplete to Populate Another Autocomplete – ASP.NET, ColdFusion, and PHP Examples
- jQuery Ajax Get XML Parsing Error: no element found Location: moz-nullprincipal


Twitter
About
28 Comments
Hey, nice script very helpful .
Thanks a lot …
Pingback: How to Create a Viral Launch Page with WordPress | Wptuts+
The only thing that caught me up is that eregi(), which you are using in isValidEmail, is deprecated as of PHP 5.3 . Otherwise, everything worked great. Exactly what I was looking for. Thanks!
@Stephen
You are correct which is why the post says to use filter_var if you have PHP 5.2 or later. Please read the entire post. It may have saved you some time.
Hey Jen,
Check out this line of code:
if(filter_var($_POST['email_ajax'], FILTER_VALIDATE_EMAIL) || filter_var($_POST['email_post'], FILTER_VALIDATE_EMAIL)) {
Update to:
if(filter_var($_POST['email_ajax'], FILTER_VALIDATE_EMAIL) ) {
And your example will work….
Great article indeed..
But I don’t prefer jQuery.post() or jQuery.get() method to do an ajax call as they don’t support error handling.
http://jquerybyexample.blogspot.com/2011/11/avoid-jquerypost-use-jqueryajax.html
I prefer jQuery.ajax() as it supports error handling as well.
Thank you for breaking this down into it’s simplest elements. You helped me get my head wrapped around jquery for the first time.
Nice post.. Thanks for sharing the entire code with us….