logo

jQuery AJAX tutorial

Add comment

This tutorial cover some of basics about jQuery and AJAX. We will build AJAX form submit where we will have 1 field. If we lave it blank and submit our form, we will get error message. If we fill it with some data we will get that text. We will also add some loader image. So first we have to create some folder structure.

Folder structure

Folder structure

After that we can start creating our files. You can download jQuery here. First we have index.php. That is our main file and it will have form. Our AJAX calls are made from that file to post.php. Here is index.php source code.

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Antispam form</title>
        <link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
    </head>

    <body>
        <div id="wrapper">
            <div id="message" style="display: none;">
            </div>
            <div id="waiting" style="display: none;">
                Please wait<br />
                <img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
            </div>
            <form action="" id="demoForm" method="post">
                <fieldset>
                    <legend>Demo form</legend>
                    <span style="font-size: 0.9em;">This ajax submit demo form.</span>
                    <p>
                        <label for="email">E-Mail:</label>
                        <input type="text" name="email" id="email" value="" />
                    </p>
                    <p>
                        <input type="submit" name="submit" id="submit" style="float: right; clear: both; margin-right: 3px;" value="Submit" />
                    </p>
                </fieldset>
            </form>
        </div>
        <script type="text/javascript" src="js/jquery/jquery-1.3.2.js"></script>
        <script type="text/javascript" src="js/ajaxSubmit.js"></script>
    </body>
</html>

This is our main.css file.

@CHARSET "UTF-8";

body {
    background-color: #f0f0f0;
}

#wrapper {
    margin: 100px auto;
    width: 310px;
}

#email {
    width: 248px;
}

#text {
    width: 248px;
    height: 70px;
}

#waiting {
    color: #767676;
    text-align: center;
}

fieldset {
    margin-top: 10px;
    background: #fff;
    border: 1px solid #c8c8c8;
    background-color: #fff;
}

legend {
    background-color: #fff;
    border-top: 1px solid #c8c8c8;
    border-right: 1px solid #c8c8c8;
    border-left: 1px solid #c8c8c8;
    font-size: 1.2em;
    padding: 0px 7px;
}

label {
    display: inline-block;
    width: 50px;
}

.success {
    width: 298px;
    background: #a5e283;
    border: #337f09 1px solid;
    padding: 5px;
}

.error {
    width: 298px;
    background: #ea7e7e;
    border: #a71010 1px solid;
    padding: 5px;
}

Now we need to create our javascript file that will do request. We are building ajaxSubmit.js file.

First we ensure that our document is loaded. After that we add event listener to our element with id #submit (that is our submit button). When we click on that button anonymous function is executed. That function makes AJAX call. When we start our AJAX call first we show our loader (id is #waiting), then we hide our form (id is #demoForm) and message if there was any (id is #message). We initialize our AJAX call and create some setting. We set our type to POST, url to post.php and dataType (data type that is returned from server) to json. Then we set our data to be sent. We provide our data as an object. Our object looks like "{name : 'value', name1: 'value1', ...}" . That object is translated into request string and sent to server as "name=value&name1=value1&...". Next we just add two more anonymous functions. They are called when our AJAX is executed successfully or when we have error. Function that is called when we have success takes 1 argument and that is data returned from server (in our case in JSON format). We hide our loader, remove any class that was there before and then add new. In our response we get and object with 2 variables (msg and error). If error is true we add class error, otherwise we add class success. After that we add our message from response to that element and show it. If our response was an error we show our form as well. Last we have error function that is called when request was not received or our AJAX call fails. It accepts 3 arguments (but they are not important to us now). In that function we hide our loader, remove class from message element, add error class, add text with message "There was an error." and show our message. We also show our form. On the end our listener function returns false. If we would not return false our form would be submitted as regular post, but since we return false it is not submited. You can read more about jQuery AJAX here. This is how our ajaxSubmit.js file looks.

$(document).ready(function(){
	$('#submit').click(function() {

		$('#waiting').show(500);
		$('#demoForm').hide(0);
		$('#message').hide(0);

		$.ajax({
			type : 'POST',
			url : 'post.php',
			dataType : 'json',
			data: {
				email : $('#email').val()
			},
			success : function(data){
				$('#waiting').hide(500);
				$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
					.text(data.msg).show(500);
				if (data.error === true)
					$('#demoForm').show(500);
			},
			error : function(XMLHttpRequest, textStatus, errorThrown) {
				$('#waiting').hide(500);
				$('#message').removeClass().addClass('error')
					.text('There was an error.').show(500);
				$('#demoForm').show(500);
			}
		});

		return false;
	});
});

Now we just need to create our file that handles requests from our AJAX call. That file is post.php (we told so to our AJAX). At the beginning we add sleep(3);. We add that just so we could see our loader show and test that it works ok. That function delays PHP script execution for x seconds (in our case 3). Since we do it ll locally our requests are processed almost instantly (about 20ms are required to process request and get response). After that we check if user has entered his e-mail address. If he did not we create new array (that array will be converted to JSON object) with keys error and msg. We set error to true and msg to "You did not enter you email.". If he did entered his e-mail address we set error to false and msg to "You've entered:" plus e-mail that he entered. At the end we convert our array to JSON object and echo it. That is response recieved by our AJAX call.

< ?php
sleep(3);

if (empty($_POST['email'])) {
	$return['error'] = true;
	$return['msg'] = 'You did not enter you email.';
}
else {
	$return['error'] = false;
	$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}

echo json_encode($return);

Here are some screenshots of our form in action.

  1. Our loader when we wait for response.
  2. When we receive our response without error.
  3. When we receive our response with error.
Loader

Loader

There is no error

There is no error

We have error

We have error

You can download source code from here or view demo here.

Thanks for reading.

Update: As Pre requested, I've created extended version. You can view it here or download here.


logo

136 comments to “jQuery AJAX tutorial”

  1. daniel says:

    tanx a lot :-* nice job

  2. joseph says:

    great

  3. rick says:

    awesome. worked the first try!!!!!

  4. Huu Dan Phan says:

    This is a great tut.
    Thanks

  5. Marc vebex says:

    I discovered this special form
    http://www.mcwehbe.com/demo.php?imenu=4

    take a look it might help you

  6. Hmm, I still don’t understand what are you trying to do. If you’re trying to submit form using Android APP, make sure you send it as a POST request.

  7. Fabio Adorno says:

    Congratulations for the code.

    It works fine on Internet.

    I just upload your code on my server.
    Look it at :

    http://axiom.com.br/PHONEGAP6/.

    I’m searching for Phonegap Solution using Ajax and Jquery.

    I’m Using Dreanweaver CS6 plugin to build an Android app.

    I just changed config.xml file ( widget )

    writing .

    After build I am testing your code directily on my device ( Galaxy – Samsung )

    So app not run !!!!!

    I simple receive a message : There was an error.

    Do you have an idea to solve this ?

    How could I discover the reason of this error ?

    Regards
    Fabio Adorno
    São Paulo – Brasil

  8. Hmm, well, it seems that’s for phones and not PHP. Can you be more specific?

  9. saranya says:

    hi i’m working in phonegap. i’m basically from hardware side and I’m new to phonegap,php. I want to create a sql database using phonegap. What language i should know to do this.are jquery,ajax needed to know?

  10. Luchoo says:

    Excelente !! Muy buena, con mas tiempo esto puede hacer maravillas :D

  11. Well, you could give yourself some task and try to complete it. Later, when you have some more knowledge, you should re factor your old code. That’s one way :)

  12. Enamul says:

    Good one.Keep it up. I know php about intermediate level, ajax and jquery found difficult. Can you suggest me how can I improve my ajax and jquery skills.
    Thanks

  13. Works fine by me…

  14. I looks realy nice, thx :)

  15. Rupesh kumar says:

    In the updated version of this demo the url is giving me wrong result. plz check it.

  16. Leon Revill says:

    Please take a look at my PHP jQuery search tutorial and let me know what you all think. It uses JSON objects to pass data from the PHP instead of sending HTML. http://www.revillwebdesign.com/php-jquery-search-tutorial/ Hope this helps someone :)

Leave a Reply


 *


 *


logo
logo
Powered by Wordpress | Designed by Elegant Themes | CopyRight ©2014 php4every1.com