4
jQuery.ajax and jQuery.post Form Submit Examples with PHP
jquery, php
Tags: forms, jquery, php
Share
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(){
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>");
}
}
});
return false;
});
});
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(){
$.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");
return false;
});
});
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:
10 Comments for jQuery.ajax and jQuery.post Form Submit Examples with PHP
[...] 4 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. Here is an example of both in action doing the same thing: form submit with email validation. The form: jQuery controls the submit for the forms. For the .ajax submission the jQuery is this: As in the .ajax example, the form is simple, only the names have been changed: 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. 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: Pretty simple, pretty handy couple of jQuery functions. Once you see it in action, you get the idea. Usual recommended jQuery and PHP reading: Copyright © 2009. All rights reserved. Download Free Article Spinner Thanks. [...]
nikos
February 4, 2010
Very useful, thanks.
Excellent "post"..no pun intended
I searched high and low to learn how to return a variable back formt the PHP script. Hard to believe that a simple "echo" does it.
Thanks much!
@Dario
You're welcome. Glad it helped. Sometimes the simplest solutions are the hardest to find. You figure it just can't be that easy…
teo
March 2, 2010
first of all thanx for the nice tut. second sorry or my bad english.
i have the same question with dario and i searched A LOT.
i want to take back from the server some data. so all i need is to do an 'echo' ? its so simple ? i mean when i use .ajax or .post i take the data to the client side from the server with an echo in the server ?so simple? :/
and ok this…but if i want to send data ? can u give me a simple example to send a string to a data.php ?
im trying to do it with $.get but doesnt work!
thanx a lot
teo
@Teo
I am not sure if you want to send form data as well. Also, I don't know how much data you need to send.
The demo in the tut sends the form data to the server by way of a post. You could add a query string to the URL for the page on the server and pick up the variables with PHP or you could add additional hidden form fields and pick up the variables exactly as the tut does.
Altaf
March 16, 2010
I am new to PHP. I have a member registration form which opens in a thick box. The code for member registration is in the same php file. On submission of the form, data should be inserted in database which is not the case right now. I have written javascript through which I am calling the following:
document.frmRegistration.submit();
but its not working. Any help is appreciated..
hey: Altaf you can insert your record to your database with out any jscript.. you can insert it through html+php..
you can use GET and POST array in php to easily get the value from the form.. you can ask mr. google about this.
Cheung
June 10, 2010
Good ….
I got what I realy need.
cj07
July 7, 2010
very nice explanation for the differences of the two.. It helped me in my work..
Leave a comment
« Override “Print Background Colors and Images” Option in Browser | jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion »

jQuery.ajax and jQuery.post Form Submit Examples with PHP – jensbits.com » Auto Post Script
October 25, 2009