jQuery.ajax and jQuery.post Form Submit Examples with PHP

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:


Demo

Posted in jquery, php. Tags: , , . Permalink. Both comments and trackbacks are closed.

25 Comments

  1. December 29, 2011 at 1:26 am | Permalink

    Nice post.. Thanks for sharing the entire code with us….

  2. December 27, 2011 at 3:07 pm | Permalink

    Thank you for breaking this down into it’s simplest elements. You helped me get my head wrapped around jquery for the first time.

  3. Jayesh
    December 1, 2011 at 1:34 am | Permalink

    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.

  4. Steve
    November 10, 2011 at 12:10 am | Permalink

    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….

  5. October 9, 2011 at 11:25 am | Permalink

    @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.

3 Trackbacks

  1. […] This file works in tandem with the JavaScript in js/init.js to post the form data. Credit goes to this super helpful tutorial for the functionality that we have modified for our needs: Jensbits.com: jQuery Ajax and jQuery Post Form Submit Examples with PHP. […]

  2. By Measuring API Documentation on the Web | Nin Labs on February 20, 2011 at 3:15 pm

    […] To answer our research questions, we performed an preliminary study, where we searched for 173 api methods from jQuery and manually inspected and analyzed the first page of search results on google (1730 search results in total). For example, we if searching for “jquery jQuery.post”, we would see results for the official api method documentation, a stackoverflow question, and a blog post. […]

  3. […] 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. […]