Vous êtes sur la page 1sur 11

AJAX

AJAX has changed the world of web development. Look at digg, facebook and gmail, thery are good examples to show the capability
of AJAX. AJAX can create a highly responsive web interface and increase the user experience.

AJAX is abbrieviated from Asynchrounous javascript and XML. It's not a new technology, but the implementation of a group of
technologies to achieve a seamless interaction between client and server.

Typically, xhtml and css to present the information, javascript is used to handle user interactions, and a server side language to
perform the users' requests (and normally return data in XML format, in this tutorial, we won't do that), and it all is happening in the
background using the Javascript XMLHttpRequest. Javascript plays a main role tie all these technologies together and create the
asynchronous interaction between client ans server.

Advantages:

 Reduce connections and bandwidth to the server, images, scripts, stylesheets only need to be downloaded once
 Reduce loading timew. User doesnt have to load pages again and again, it all happens in a same page!
 Increase responsiveness and end user experiences.

Usability Guidelines:

 Always provide feedback to user. Let user know the server is processing the request. Indicate that using message or loading
icon.
 Prepare a plan to those users without Javascript support.

Introduction
So, you know about the goodness of AJAX. Let's learn a simple way to implement it.

In this tutorial, we will learn form submission using jQuery without navigate out from the page. It accepts user input, processes it and
sends it to a php file called "process.php". The PHP script will send a notification email to the recipient. Of course, in case browser
couldn't support javascript/XMLHttpRequest, we have a second plan ready, the form will submit the data using the normal form
submission.

How do we do that? Easy, we specified POST and ACTION attributes in the FORM element, if browsers couldn't support it, that will
submit the form straight away. If the browsers could support it, the javascript will cancel the submit button default behaviour. And we
need to code the PHP script to support both GET and POST methods and produce the result accordingly.

1. HTML
In this sample, I'll keep everything as simple as possible. This is how it looks like

view plaincopy to clipboardprint?

1. <div class="block">  
2. <div class="done">  
3. <b>Thank you !</b> We have received your message.   
4. </div>  
5.     <div class="form">  
6.     <form method="post" action="process.php">  
7.     <div class="element">  
8.         <label>Name</label>  
9.         <input type="text" name="name" class="text" />  
10.     </div>  
11.     <div class="element">  
12.         <label>Email</label>  
13.         <input type="text" name="email" class="text" />  
14.     </div>  
15.     <div class="element">  
16.         <label>Website</label>  
17.         <input type="text" name="website" class="text" />  
18.     </div>  
19.     <div class="element">  
20.         <label>Comment</label>  
21.         <textarea name="comment" class="text textarea" /></textarea>  
22.     </div>  
23.     <div class="element">  
24.           
25.         <input type="submit" id="submit"/>  
26.         <div class="loading"></div>  
27.     </div>  
28.     </form>  
29.     </div>  
30. </div>  
31. <div class="clear"></div>  

2. CSS
I'm using CSS to make the 2 columns layout - LABEL and Form Elements. Also, some important classes:

 .hightlight: Error indicator. if user had not entered anything in the textfield, it will highlight it and display an error icon
 .loading: Loading animation icon. After user clicked on submit, if no errors were found, this icon will be displayed next to the
submit button
 .done: Success message. If the form is submitted successfully, display show this class

view plaincopy to clipboardprint?

1. body{text-align:center;}  
2.   
3. .clear {clear:both}  
4.   
5. .block {  
6.     width:400px;  
7.     margin:0 auto;  
8.     text-align:left;  
9. }  
10. .element * {  
11.     padding:5px;   
12.     margin:2px;   
13.     font-family:arial;  
14.     font-size:12px;  
15. }  
16. .element label {  
17.     float:left;   
18.     width:75px;  
19.     font-weight:700  
20. }  
21. .element input.text {  
22.     float:left;   
23.     width:270px;  
24.     padding-left:20px;  
25. }  
26. .element .textarea {  
27.     height:120px;   
28.     width:270px;  
29.     padding-left:20px;  
30. }  
31. .element .hightlight {  
32.     border:2px solid #9F1319;  
33.     background:url(iconCaution.gif) no-repeat 2px  
34. }  
35. .element #submit {  
36.     float:right;  
37.     margin-right:10px;  
38. }  
39. .loading {  
40.     float:right;   
41.     background:url(ajax-loader.gif) no-repeat 1px;   
42.     height:28px;   
43.     width:28px;   
44.     display:none;  
45. }  
46. .done {  
47.     background:url(iconIdea.gif) no-repeat 2px;   
48.     padding-left:20px;  
49.     font-family:arial;  
50.     font-size:12px;   
51.     width:70%;   
52.     margin:20px auto;   
53.     display:none  
54. }  

3. Javascript
Finally, the Javascript code. I have added comments in each line to explain what it does.

First, we need a simple validation to ensure user has key in something. We can add more validations, like, email validation, valid
character validation, length validation and so on. And it's a good practise to encode the data into URL friendly format as well.

What the code does:

 Get user's input


 Validate the data, if error found, add the hightlight class, and stop the script
 If no errors were found, all text field will be disabled and format the data to be passed to jQuery ajax method
 jQuery will appened the data to process.php, so it will look something like this:

http://[your-website-url]/process.php?
name=kevin&email=kevin@test.com&website=http://www.queness.com&comment=Testing%20of%20Ajax%20Form
%20Submission

in fact, you can execute the process.php with that url.


 process.php will return either 1 or 0, if 1 it meant mail was sent successfully, otherwise, mail was not sent.
 If suceed, the form will be hidden and a message is displayed.

view plaincopy to clipboardprint?

1. $(document).ready(function() {  
2.       
3.     //if submit button is clicked  
4.     $('#submit').click(function () {          
5.           
6.         //Get the data from all the fields  
7.         var name = $('input[name=name]');  
8.         var email = $('input[name=email]');  
9.         var website = $('input[name=website]');  
10.         var comment = $('textarea[name=comment]');  
11.   
12.         //Simple validation to make sure user entered something  
13.         //If error found, add hightlight class to the text field  
14.         if (name.val()=='') {  
15.             name.addClass('hightlight');  
16.             return false;  
17.         } else name.removeClass('hightlight');  
18.           
19.         if (email.val()=='') {  
20.             email.addClass('hightlight');  
21.             return false;  
22.         } else email.removeClass('hightlight');  
23.           
24.         if (comment.val()=='') {  
25.             comment.addClass('hightlight');  
26.             return false;  
27.         } else comment.removeClass('hightlight');  
28.           
29.         //organize the data properly  
30.         var data = 'name=' + name.val() + '&email=' + email.val() + '&website='  
31.         + website.val() + '&comment='  + encodeURIComponent(comment.val());  
32.           
33.         //disabled all the text fields  
34.         $('.text').attr('disabled','true');  
35.           
36.         //show the loading sign  
37.         $('.loading').show();  
38.           
39.         //start the ajax  
40.         $.ajax({  
41.             //this is the php file that processes the data and send mail  
42.             url: "process.php",   
43.               
44.             //GET method is used  
45.             type: "GET",  
46.   
47.             //pass the data           
48.             data: data,       
49.               
50.             //Do not cache the page  
51.             cache: false,  
52.               
53.             //success  
54.             success: function (html) {                
55.                 //if process.php returned 1/true (send mail success)  
56.                 if (html==1) {                    
57.                     //hide the form  
58.                     $('.form').fadeOut('slow');                   
59.                       
60.                     //show the success message  
61.                     $('.done').fadeIn('slow');  
62.                       
63.                 //if process.php returned 0/false (send mail failed)  
64.                 } else alert('Sorry, unexpected error. Please try again later.');                 
65.             }         
66.         });  
67.           
68.         //cancel the submit button default behaviours  
69.         return false;  
70.     });   
71. });   

4. PHP
This PHP code can accomodate different type of submissions (POST and GET). If the user submitted the form using jQuery,
process.php will get the data from GET. and if the browser couldn't run javascript, the data will be sent using POST. What it does:

 Retrieve user's input from either GET or POST method


 If POST, set the $post variable to 1. This is to display the message instead of return the result
 Then, perform the server side validation if the form was submitted using POST
 If no errors were found, organize the data into a html email template and send it to the email we have specified.
 Display the message if POST is used. Display result (either 1 or 0) if GET is used

view plaincopy to clipboardprint?

1. <?php  
2.   
3. //Retrieve form data.   
4. //GET - user submitted data using AJAX  
5. //POST - in case user does not support javascript, we'll use POST instead  
6. $name = ($_GET['name']) ? $_GET['name'] : $_POST['name'];  
7. $email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];  
8. $website = ($_GET['website']) ?$_GET['website'] : $_POST['website'];  
9. $comment = ($_GET['comment']) ?$_GET['comment'] : $_POST['comment'];  
10.   
11. //flag to indicate which method it uses. If POST set it to 1  
12. if ($_POST) $post=1;  
13.   
14. //Simple server side validation for POST data, of course,   
15. //you should validate the email  
16. if (!$name) $errors[count($errors)] = 'Please enter your name.';  
17. if (!$email) $errors[count($errors)] = 'Please enter your email.';   
18. if (!$comment) $errors[count($errors)] = 'Please enter your comment.';   
19.   
20. //if the errors array is empty, send the mail  
21. if (!$errors) {  
22.   
23.     //recipient - change this to your name and email  
24.     $to = 'Your Name <your@email.com>';     
25.     //sender  
26.     $from = $name . ' <' . $email . '>';  
27.       
28.     //subject and the html message  
29.     $subject = 'Comment from ' . $name;   
30.     $message = '  
31.     <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   
32.     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
33.     <html xmlns="http://www.w3.org/1999/xhtml">  
34.     <head></head>  
35.     <body>  
36.     <table>  
37.         <tr><td>Name</td><td>' . $name . '</td></tr>  
38.         <tr><td>Email</td><td>' . $email . '</td></tr>  
39.         <tr><td>Website</td><td>' . $website . '</td></tr>  
40.         <tr><td>Comment</td><td>' . nl2br($comment) . '</td></tr>  
41.     </table>  
42.     </body>  
43.     </html>';  
44.   
45.     //send the mail  
46.     $result = sendmail($to, $subject, $message, $from);  
47.       
48.     //if POST was used, display the message straight away  
49.     if ($_POST) {  
50.         if ($result) echo 'Thank you! We have received your message.';  
51.         else echo 'Sorry, unexpected error. Please try again later';  
52.           
53.     //else if GET was used, return the boolean value so that   
54.     //ajax script can react accordingly  
55.     //1 means success, 0 means failed  
56.     } else {  
57.         echo $result;     
58.     }  
59.   
60. //if the errors array has values  
61. } else {  
62.     //display the errors message  
63.     for ($i=0; $i<count($errors); $i++) echo $errors[$i] . '<br/>';  
64.     echo '<a href="form.php">Back</a>';  
65.     exit;  
66. }  
67.   
68.   
69. //Simple mail function with HTML header  
70. function sendmail($to, $subject, $message, $from) {  
71.     $headers = "MIME-Version: 1.0" . "\r\n";  
72.     $headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";  
73.     $headers .= 'From: ' . $from . "\r\n";  
74.       
75.     $result = mail($to,$subject,$message,$headers);  
76.       
77.     if ($result) return 1;  
78.     else return 0;  
79. }  
80. ?>  

Conclusion
Now you know how to build a ajax based form submission that will work even if the browser doesnt support javascript using jQuery.
Make sure you check out the demo and download the source code to play with it. Last but not least, I need your support :) If you like
this article, please help me to promote it by adding this post into your bookmark. Or you can subscribe to my RSS for more posts.
Thanks!

Vous aimerez peut-être aussi