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. StephenE
    October 9, 2011 at 9:05 am | Permalink

    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!

  2. ige
    September 27, 2011 at 1:20 pm | Permalink

    Hey, nice script very helpful .
    Thanks a lot …

  3. Alfa9
    July 19, 2011 at 10:52 pm | Permalink

    Thank you very much !!
    this helped me alot :D
    you rock dude !

  4. Bharatsatya
    July 12, 2011 at 12:58 am | Permalink

    Very nice,thanks a lot

  5. July 1, 2011 at 7:06 am | Permalink

    really thanks

    i got a very useful lesson at here

    what i wanted that i got

  6. April 13, 2011 at 2:33 pm | Permalink

    nice script…

  7. February 28, 2011 at 11:48 am | Permalink

    Thank you. Simple and clear.

  8. February 3, 2011 at 2:20 am | Permalink

    Thanks for article with Example …………….cool post dude great work :-)

  9. January 6, 2011 at 8:41 am | Permalink

    @sanga
    No, I cannot. I do not know what specific problem you are having. The download files use PHP 5.2 and up. Check your PHP version. There is a note in the article on what code to use if you have an earlier version of PHP.

  10. sanga
    January 6, 2011 at 1:49 am | Permalink

    downloa is not work can you tell me why

3 Trackbacks