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

 

Further Reading:

  1. jQuery.ajax and jQuery.post Form Submit Examples with ColdFusion
  2. Modal Confirmation Dialog on Form Submit: Javascript, jQuery UI, and Thickbox Varieties
  3. Using jQuery Autocomplete to Populate Another Autocomplete – ASP.NET, ColdFusion, and PHP Examples
  4. jQuery Ajax Get XML Parsing Error: no element found Location: moz-nullprincipal
Posted in jquery, php. Tags: , , . Permalink. Both comments and trackbacks are closed.

25 Comments

  1. Márcio
    September 27, 2010 at 11:26 am | Permalink

    On your last example, instead of filter_var can we use filter_input? I believe so… :)

  2. cj07
    July 7, 2010 at 1:00 am | Permalink

    very nice explanation for the differences of the two.. It helped me in my work..

  3. Cheung
    June 10, 2010 at 3:52 am | Permalink

    Good ….

    I got what I realy need.

  4. April 20, 2010 at 3:14 am | Permalink

    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.

  5. Altaf
    March 16, 2010 at 7:57 am | Permalink

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

  6. March 2, 2010 at 1:01 pm | Permalink

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

  7. teo
    March 2, 2010 at 11:30 am | Permalink

    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

  8. February 11, 2010 at 8:06 pm | Permalink

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

  9. February 10, 2010 at 3:42 pm | Permalink

    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!

  10. nikos
    February 4, 2010 at 4:49 am | Permalink

    Very useful, thanks.

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