Tuesday, October 22, 2013

jQuery AJAX tutorial

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.
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.
01.< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
03.<html xmlns="http://www.w3.org/1999/xhtml">
04.<head>
05.<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
06.<title>Antispam form</title>
07.<link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
08.</head>
09. 
10.<body>
11.<div id="wrapper">
12.<div id="message" style="display: none;">
13.</div>
14.<div id="waiting" style="display: none;">
15.Please wait<br />
16.<img src="images/ajax-loader.gif" title="Loader" alt="Loader" />
17.</div>
18.<form action="" id="demoForm" method="post">
19.<fieldset>
20.<legend>Demo form</legend>
21.<span style="font-size: 0.9em;">This ajax submit demo form.</span>
22.<p>
23.<label for="email">E-Mail:</label>
24.<input type="text" name="email" id="email" value="" />
25.</p>
26.<p>
27.<input type="submit" name="submit" id="submit" style="float: right; clear: both; margin-right: 3px;" value="Submit" />
28.</p>
29.</fieldset>
30.</form>
31.</div>
32.<script type="text/javascript" src="js/jquery/jquery-1.3.2.js"></script>
33.<script type="text/javascript" src="js/ajaxSubmit.js"></script>
34.</body>
35.</html>
This is our main.css file.
01.@CHARSET "UTF-8";
02. 
03.body {
04.background-color: #f0f0f0;
05.}
06. 
07.#wrapper {
08.margin: 100px auto;
09.width: 310px;
10.}
11. 
12.#email {
13.width: 248px;
14.}
15. 
16.#text {
17.width: 248px;
18.height: 70px;
19.}
20. 
21.#waiting {
22.color: #767676;
23.text-align: center;
24.}
25. 
26.fieldset {
27.margin-top: 10px;
28.background: #fff;
29.border: 1px solid #c8c8c8;
30.background-color: #fff;
31.}
32. 
33.legend {
34.background-color: #fff;
35.border-top: 1px solid #c8c8c8;
36.border-right: 1px solid #c8c8c8;
37.border-left: 1px solid #c8c8c8;
38.font-size: 1.2em;
39.padding: 0px 7px;
40.}
41. 
42.label {
43.display: inline-block;
44.width: 50px;
45.}
46. 
47..success {
48.width: 298px;
49.background: #a5e283;
50.border: #337f09 1px solid;
51.padding: 5px;
52.}
53. 
54..error {
55.width: 298px;
56.background: #ea7e7e;
57.border: #a71010 1px solid;
58.padding: 5px;
59.}
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.
01.$(document).ready(function(){
02.$('#submit').click(function() {
03. 
04.$('#waiting').show(500);
05.$('#demoForm').hide(0);
06.$('#message').hide(0);
07. 
08.$.ajax({
09.type : 'POST',
10.url : 'post.php',
11.dataType : 'json',
12.data: {
13.email : $('#email').val()
14.},
15.success : function(data){
16.$('#waiting').hide(500);
17.$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
18..text(data.msg).show(500);
19.if (data.error === true)
20.$('#demoForm').show(500);
21.},
22.error : function(XMLHttpRequest, textStatus, errorThrown) {
23.$('#waiting').hide(500);
24.$('#message').removeClass().addClass('error')
25..text('There was an error.').show(500);
26.$('#demoForm').show(500);
27.}
28.});
29. 
30.return false;
31.});
32.});
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.
01.< ?php
02.sleep(3);
03. 
04.if (empty($_POST['email'])) {
05.$return['error'] = true;
06.$return['msg'] = 'You did not enter you email.';
07.}
08.else {
09.$return['error'] = false;
10.$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
11.}
12. 
13.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.