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.

Related Posts
  • 09.09.2009 -- AJAX Multi-Level Comments (57)
    In this tutorial we will create multi level comments. You must have seen comments on youtube and tha...
  • 16.07.2010 -- Packt Special Offer (0)
    Packt Publishing has new offer for this hot summer. Have a someones birthday soon and don't know ...
  • 23.12.2009 -- Learning Resources (0)
    Reader Satish requested a list of tutorials where he could learn about PHP, MySQL and jQuery. Since ...
  • 16.07.2009 -- Advanced PHP User Login (19)
    If you ever had a bank account you are familiar with TAN-s (Transaction Authentication Number). What...
  • 30.12.2009 -- Ext JS 3.0 Cookbook (3)
    As I announced before, I've got a promo version of a book Ext JS 3.0 Cookbook from PacktPub. I final...
  • 17.11.2009 -- jQuery Search Content (6)
    In this tutorial I'll show you how you can create jQuery plugin that will search for some words in t...
  • 22.10.2009 -- jQuery Basic Tutorial (2)
    User named Enrho requested a tutorial that will explain some basics in jQuery. This will be a very s...

logo

115 comments to “jQuery AJAX tutorial”

  1. Add me to msn (zlikavac32@gmail.com) or to skype (zlikavac32) and I’ll help you there. Hard to do it from here.

  2. Pre says:

    thanks for the links bro, but this is a bit above my skill level. I’ve tried and tried to have your script validate everything server side, but it lets some blank fields go through. Check it out on the sign up from http://www.gamezy.com, I used a different script for the log in, I can’t get that script to send back my own custom messages. you can log in using 11@gamezy.com password 12345 then direct your browser to progamernew.php after logging in. Click the post a challenge button. For what ever reason the scripts sends empty values through just fine, even though to tell it not to.

  3. Pre says:

    It works fine bro. I’m trying to mesh it with a form validation I thing that’s why.
    I only want to use server side jason to double check important fields but I’d like most of the fields validated before submission. Can’t find a script that will work with it.

  4. What kind of errors? Can you send me screens shoots to msufflaj32@gmail.com?

  5. Pre says:

    Sup Bro,
    I’d got it to work, then it would work sometimes then I got a headache and just abandoned it. But then I searched and searched and couldn’t find another that I could get to work at least once. Everything is right, followed your tuts step by step, but it just keeps saying error. What is Up?

  6. You would use it like any other POST request. That post.php is just an example that will show you that you request was executed successfully.

    After you check for errors you can use mysql functions to connect and execute query.

    You can check this tutorial to see how we do database stuff.

  7. dudeone says:

    how would i use this to actually post values to a database?

    also, on the post.php page, how do i alter the values within the if statement to do an action like redirect to another page?

  8. Glad you got it working :)

  9. Pre says:

    I got it to work bro, I didn’t have php5 installed on my server, had to upgrade. Great script.

  10. I’ve added link to extended tutorial at bottom of my site. If you still have errors just send me e-mail with screen shoot or if you have firebug, errors that it says there.

  11. Pre says:

    I’m using firefox, it just keeps telling me there is an error. could you update the form please so I could see how more fields are added, your example only shows one field. I’ve viewed the source on this site copy it and it still tells me there is an error, without submitting the form.

  12. It works for me in FF and IE. Which browser do you use?

  13. Pre says:

    Dude you script doesn’t work, it doesn’t even work with the files you provided.

  14. [...] is code that handles AJAX requests. I don’t want to repeat myself so check this tutorial in order to know what’s going on. I don’t want to explain twice how this is [...]

  15. Does your ajax_handler.php really retun JSON object format?

  16. sand says:

    Hello I have been trying something like this. just the value of my input field stays empty.

    Look here for details:
    http://stackoverflow.com/questions/1118691/few-questions-about-auto-fill-search-terms

  17. [...] more here:  jQuery AJAX tutorial – PHP for everyone SHARETHIS.addEntry({ title: "jQuery AJAX tutorial – PHP for everyone", url: [...]

  18. [...] View original post here: jQuery AJAX tutorial – PHP for everyone [...]

  19. [...] the original here:  jQuery AJAX tutorial – PHP for everyone Posted in PHP | Tags: ajax, basics-about, blank-and, form, form-submit, lave-it-blank, [...]

Leave a Reply


 *


 *


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