Itroduced ToThe Ajax................



Ajax Tutorial
Ajax is a catchy name for a type of programming made popular in 2005 by Google and other big web developers. Ajax loosely stands for Asynchronous Javascript And XML, but that just sounds like techno jargon to many people.

Ajax - Javascript on Steroids

When javascript was released, people loved all the cool things you could do with the web browser to make a more user-friendly experience. You could do form validation, quirky popup messages, make cool web tools and more. However, Javascript had no way of sending information between the web browser and the web server.
If you wanted to get any information from a database on the server, or send user information to a server-side script like PHP, you had to make an HTML form to GET or POST data to the server. The user would then have to click "Submit", wait for the server to respond, then a new page would load with the results. I'm sure we have all gotten slightly annoyed when having to wait for especially slow websites!
Ajax attempts to remedy this problem by letting your Javascript communicate directly with the server, using a special Javascript object XMLHttpRequest. With this object, your Javascript can get information from the server without having to load a new page!

Ajax - Is That It?

Pretty much. By using the programming practice termed "Ajax" you will be able to trade data, with a web server, without having to load a new page. Instead of Ajax being seen as "The New Way to Develop Websites", it should instead be seen as another weapon to add to your programming arsenal.
This tutorial will introduce you to the basics of Ajax and show you how to send and receive data from a server without using a "Submit" button approach.

Ajax - Recommended Knowledge

Ajax can be quite confusing to someone with little web programming experience. It is highly recommended that you are familiar with HTML and Javascript before attempting this tutorial.

Ajax - Creating an HTML Form

Before we can start getting to the exciting new stuff, we must first make a standard HTML form (no submit button though!). This form will be spiced up in later with a hint of Ajax, but for now let's just make a solid, basic HTML form with a couple inputs.

Ajax - Do You Have the Time?

To keep this Ajax easy to understand, we are going to be creating an HTML form that has two text fields: name and time. The name field will be filled in by the user, while the time field will be filled in using Ajax.
Below is the HTML code for your "order.html" webpage. If you would like to refresh your knowledge of forms, then check out our HTML forms lesson.

order.html HTML Code:

<html>
<body>
 
<form name='myForm'>
Name: <input type='text' name='username' /> <br />
Time: <input type='text' name='time' />
</form>
 
</body>
</html>
Save this file as "order.html"

Ajax - Where's the Submit Button?

That's the great thing about Ajax, you do not need a form submit button to send the user's data to the server. We are going to be using our "Javascript on Steroids" to get and submit data with the server.
Now that we have our HTML form, we can dive deeper into the Ajax jungle and try to discover what we're facing.

Ajax - Browser Support

This lesson includes one of the largest hurdles for aspiring Ajax programmers: browser support. It would be nice if all the web browsers required the same Javascript code to use Ajax, but life isn't fair and you've got your work cut out for you!
This lesson will show you how to create the keystone of Ajax; the XMLHttpRequest object. Not only will you know how to make this important Ajax object, but you will also know how to make it compatible with all the popular browsers: Internet Explorer, Opera, Firefox, and Safari.

Ajax - Try/Catch Blocks of Code

To create this important Ajax object, you are going to have to use a special programming technique known as "try and catch". Basically it attempts to "try" a piece of code and if that piece causes an error it "catches" the error and keeps going. Normally when an error occurs the code will stop running, however, the "catch" eats up the error and lets the code continue.
In the following code we are going to "try" three different ways to make a new XMLHttpRequest object. Every time we fail and get an error, we will catch the error and try the next a different command.
Note: If our "try" is successful then the "catch" code will not be run because it is only used when there is an error.

order.html Javacsript Code:

<html>
<body>
 
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
               // Opera 8.0+, Firefox, Safari
               ajaxRequest = new XMLHttpRequest();
        } catch (e){
               // Internet Explorer Browsers
               try{
                       ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {
                       try{
                               ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                       } catch (e){
                               // Something went wrong
                               alert("Your browser broke!");
                               return false;
                       }
               }
        }
}
//-->
</script>
 
 
<form name='myForm'>
Name: <input type='text' name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>
In the above Javascript code, we try three times to make our XMLHttpRequest object. Our first attempt:
  • ajaxRequest = new XMLHttpRequest();
is for the Opera 8.0+, Firefox and Safari browsers. If that fails we try two more times to make the correct object for an Internet Explorer browser with:
  • ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
  • ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");>
If that doesn't work, then they are using a very outdated browser that doesn't support XMLHttpRequest, which also means it doesn't support Ajax.
Most likely though, our variable ajaxRequest will now be set to whatever XMLHttpRequest standard the browser uses and we can start sending data to the server.

Ajax - That Browser Specific Code is Confusing

The code in this lesson was quite complex, but the good thing is that you can just copy and paste this code and don't really have to understand it. I bet you wish I would have told you that at the beginning of the lesson!
The next lesson will teach you how to use your XMLHttpRequest object (which is currently stored in ajaxRequest variable) to communicate with the server.

Ajax - XMLHttpRequest Object

In the Previous Lesson you learned how to create an XMLHttpRequest object based on the type of web browser being used. This lesson will show you how to use your object to communicate directly with the server!

Ajax - onreadystatechange Property

Before we even think about sending data to the server, we must first write a function that will be able to receive information. This function will be used to catch the data that is returned by the server.
The XMLHttpRequest object has a special property called onreadystatechange. onreadystatechange stores the function that will process the response from the server. The following code defines an empty function and sets the onreadystatechange property at the same time!
We will be filling this function in throughout the lesson, as you learn more about the XMLHttpRequest object.

Javascript Code:

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
        // We still need to write some code here
}
This property, onreadystatechange, stores a function. As the name sort of implies, every time the "ready state" changes this function will be executed. What is this "ready state" and is it any use to us?

Ajax - readyState Property

The XMLHttpRequest object has another property called readyState. This is where the status of our server's response is stored. The response can be processing, downloading or completed. Each time the readyState changes then our onreadystatechange function executes.
The only readyState that we are going to care about in this lesson is when our response is complete and we can get our hands on that information. So let's add an If Statement to our function to check if the response is complete.
Note: When the property readyState is 4 that means the response is complete and we can get our data.

Javascript Code:

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
               // Get the data from the server's response
        }
}
Now that we know how to check if the response is complete, we can access the property that stores the server's response, responseText.

Ajax - responseText Property

For simple Ajax applications, like this tutorial describes, you can retrieve the server's response by using the responseText property. Using a little bit of Javascript and HTML forms we can change our text box to equal responseText.
In case you forgot, this tutorial is using Ajax to set an HTML text box to the server's time. The HTML input we want to change is the "time" text box. Here's a little refresher on how to access form inputs with Javascript:
  • document.FormName.InputName.value
Our form's name is "myForm" and the text box is "time". Below is the code that will set our "time" text box to the server's time.

Javascript Code:

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
               document.myForm.time.value = ajaxRequest.responseText;
        }
}
Phew! That was a lot of new things we had to use to get our server's response, but now we can rest easy knowing we are ready to send off a request to the server. Using Ajax, we can now ask our server for some data!

Ajax - Sending a Request for Information

Now that our onreadystatechange property has a proper response-handling function, we can send our request. Sending a request is comprised of two steps:
  1. Specify the URL of server-side script that will be used in our Ajax application.
  2. Use the send function to send off the request.
Our simple PHP script, that we have yet to write, will be called "serverTime.php", so we can already do step 1. The URL is set using the open method, which takes three arguments. The second argument is the important one, as it is the URL of our PHP script.
Assuming that the HTML and PHP files are in the same directory, the code would be:

Javascript Code:

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
               document.myForm.time.value = ajaxRequest.responseText;
        }
}
ajaxRequest.open("GET", "serverTime.php", true);
With all of our Javascript setup work complete, we can then use the send method to send our request to the server.

Javascript Code:

// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
        if(ajaxRequest.readyState == 4){
               document.myForm.time.value = ajaxRequest.responseText;
        }
}
ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null); 

Ajax - Finishing up "order.html"

Before we plug in our freshly written Javascript code into the "order.html" file, we need some way for the visitor to run our Ajax function. It might be kinda cool if our Ajax did its magic while the user was doing something on our webpage, so let's have our function run after the user enters their name.
Using the onChange attribute, we can make it so our function is called whenever the user makes a change to the "username" text box.

Javascript Code:

<input type='text' onChange="ajaxFunction();" name='username' /> <br />
OK, now we are ready to completely update our "order.html" file to be 100% Ajax ready.

order.html Updated Code:

<html>
<body>
 
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
               // Opera 8.0+, Firefox, Safari
               ajaxRequest = new XMLHttpRequest();
        } catch (e){
               // Internet Explorer Browsers
               try{
                       ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {
                       try{
                               ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                       } catch (e){
                               // Something went wrong
                               alert("Your browser broke!");
                               return false;
                       }
               }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
               if(ajaxRequest.readyState == 4){
                       document.myForm.time.value = ajaxRequest.responseText;
               }
        }
        ajaxRequest.open("GET", "serverTime.php", true);
        ajaxRequest.send(null); 
}
 
//-->
</script>
 
 
 
<form name='myForm'>
Name: <input type='text' onChange="ajaxFunction();" name='username' /> <br />
Time: <input type='text' name='time' />
</form>
</body>
</html>

Ajax - Final Step

There were a lot of key steps covered in this lesson, so don't worry if you have to go back and read a few sections more than once. When you're ready you can move on to the final step of making our Ajax complete: writing the "serverTime.php" script.

Ajax - Server-Side PHP Script

We completed the "order.html" file in the Previous Lesson, but we had our Ajax linking to a PHP script that did not yet exist. This lesson will walk you through the process of creating a simple PHP script that displays the current server time.

Ajax - serverTime.php File

The XMLHttpRequest property, responseText, will store the data that this PHP script displays to the browser, so all we want this script to do is Echo the current time. If you would like a refresher on how to use PHP's date function, you can check out our PHP Date Tutorial. The php code below should be saved in the same directory as "order.html".

serverTime.php PHP Code:

<?php
echo date("H:i:s"); 
?>

Ajax - Run Your Ajax!

Below is a working version of the simple, yet super cool, Ajax application you have just created! To test it out just type some text into the "Name:" text box, then click inside the "Time:" text box.

Display of order.html:

Name:
Time:
Sweet! The time text box pulled down the server's time from "serverTime.php" without having to reload the entire page! Congratulations you've just written your first fully-functional Ajax application!

Ajax - Continued Learning

That's all for now folks! If you're feeling adventerous about taking your Ajax skills to the next level, then I highly recommend you check out IBM's Master Ajax Series.


ADVANCED AJAX...



Ajax - MySQL Database
We already know how to run an external PHP script with AJAX, so let's take it to the next level and pull some data down from a MySQL database. Our "order.html" file and PHP script will have to be updated and we also need to make a new database.

Create the MySQL Table

To clearly illustrate how easy it is to access information from a database using Ajax, we are going to build MySQL queries on the fly and display the results on "order.html".
Create a new database or use an existing one and then import the table ajax_example.sql to that database. This sql file will create the table ajax_example and insert all the data rows. The table has four columns:
  • ae_name - The name of the person
  • ae_age - Person's age
  • ae_sex - The gender of the person
  • ae_wpm - The words per minute that person can type

Update order.html

We want to be able to build queries from our HTML file, so there are a few form elements that will need to be added. The three inputs we are going to implement are:
  • Maximum Age (Text Input) - Let the user select the maximum age to be returned.
  • Maximum WPM (Text Input) - Let the user select the maximum wpm to returned.
  • Gender (Select Input) - Let the user select the gender of a valid person.

order.html HTML/Javascript Code:

<html>
<body>
 
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
               // Opera 8.0+, Firefox, Safari
               ajaxRequest = new XMLHttpRequest();
        } catch (e){
               // Internet Explorer Browsers
               try{
                       ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {
                       try{
                               ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                       } catch (e){
                               // Something went wrong
                               alert("Your browser broke!");
                               return false;
                       }
               }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
               if(ajaxRequest.readyState == 4){
                       document.myForm.time.value = ajaxRequest.responseText;
               }
        }
        var age = document.getElementById('age').value;
        var wpm = document.getElementById('wpm').value;
        var sex = document.getElementById('sex').value;
        var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
        ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
        ajaxRequest.send(null); 
}
 
//-->
</script>
 
 
 
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option>m</option>
<option>f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
</body>
</html>
If the new Javascript code is foreign to you, be sure to check out our lesson on Javascript's getElementById Function.
With our new Javascript code
var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
we have built a query string to pass along the information from our HTML form to our PHP script.

Ajax - Passing Variables via Query String

A query string is a way of passing information by appending data onto the URL. You may have often seen it on the web, it's all the information that appears after a question mark "?". When you submit a form using GET it builds a query string, all we're doing here is manually building our own.
  • http://www.arya2014b.blogspot.in/
The left side of the equals operator is the variable name and the right side is the variable's value. Also, each variable is separated with an ampersand &.
For example, if we wanted to send the variables age, sex, and wpm with values 20, f, 40 to our PHP script ajax-example.php then our URL would look like:
  • http://www.arya2014b.blogspot.in /
  •  Now we need to build a new PHP script to take these variables and run a MySQL query for us.

Ajax - Create ajax-example.php Script

We already changed the destination URL in our ajaxRequest.open method, now we need to make a script to grab those variables from the query string and execute a MySQL Query We're also going to use a special function mysql_real_escape_string to prevent any harmful user input from doing something they aren't supposed to (we're going to take steps against SQL Injection).

ajax-example.php Code:

<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbpass = "dbpassword";
$dbname = "dbname";
        //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbpass);
        //Select Database
mysql_select_db($dbname) or die(mysql_error());
        // Retrieve data from Query String
$age = $_GET['age'];
$sex = $_GET['sex'];
$wpm = $_GET['wpm'];
        // Escape User Input to help prevent SQL Injection
$age = mysql_real_escape_string($age);
$sex = mysql_real_escape_string($sex);
$wpm = mysql_real_escape_string($wpm);
        //build query
$query = "SELECT * FROM ajax_example WHERE ae_sex = '$sex'";
if(is_numeric($age))
        $query .= " AND ae_age <= $age";
if(is_numeric($wpm))
        $query .= " AND ae_wpm <= $wpm";
        //Execute query
$qry_result = mysql_query($query) or die(mysql_error());
 
        //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";
 
        // Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
        $display_string .= "<tr>";
        $display_string .= "<td>$row[ae_name]</td>";
        $display_string .= "<td>$row[ae_age]</td>";
        $display_string .= "<td>$row[ae_sex]</td>";
        $display_string .= "<td>$row[ae_wpm]</td>";
        $display_string .= "</tr>";
        
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

The Next Step - Updating order.html

We have completed our initial order.html and ajax-example.php setup, now we just need our order.html page to update correctly when a query is returned. We'll be using a couple advanced Javascript functions to update a segment of order.html with the MySQL result display_string.

Ajax - Javascript Techniques

The real trick of Ajax is updating a segment of the page without actually having to reload the entire page. This little trick is often done by utilizing a Javascript property known as innerHTML. Each HTML element on a page has an innerHTML associated with it that can be changed at any time. For us, we need to update it when our ajax-example.php script has finished executing.

Updating the order.html Page

First we need to create a new div on this page that will contain the results of the query. After we have that in place we can update the div's innerHTML with the information returned by ajax-example.php. Remember that this result is stored inside ajaxRequest.responseText.

order.html HTML/Javascript Code:

<html>
<body>
 
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
        var ajaxRequest;  // The variable that makes Ajax possible!
        
        try{
               // Opera 8.0+, Firefox, Safari
               ajaxRequest = new XMLHttpRequest();
        } catch (e){
               // Internet Explorer Browsers
               try{
                       ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
               } catch (e) {
                       try{
                               ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
                       } catch (e){
                               // Something went wrong
                               alert("Your browser broke!");
                               return false;
                       }
               }
        }
        // Create a function that will receive data sent from the server
        ajaxRequest.onreadystatechange = function(){
               if(ajaxRequest.readyState == 4){
                       var ajaxDisplay = document.getElementById('ajaxDiv');
                       ajaxDisplay.innerHTML = ajaxRequest.responseText;
               }
        }
        var age = document.getElementById('age').value;
        var wpm = document.getElementById('wpm').value;
        var sex = document.getElementById('sex').value;
        var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
        ajaxRequest.open("GET", "ajax-example.php" + queryString, true);
        ajaxRequest.send(null); 
}
 
//-->
</script>
 
 
 
<form name='myForm'>
Max Age: <input type='text' id='age' /> <br />
Max WPM: <input type='text' id='wpm' />
<br />
Sex: <select id='sex'>
<option value='m'>m</option>
<option value='f'>f</option>
</select>
<input type='button' onclick='ajaxFunction()' value='Query MySQL' />
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

Quick Ajax Recap

So far we have created a new MySQL table, written a new PHP script and updated order.html twice. If you have followed the directions in the Ajax MySQL lesson and created the MySQL table ajax_example and ajax-example.php script then the updated order.html page will be functional.

Ajax Javascript Lessons

If you want to update a non form element, be sure to use the innerHTML attribute that is associated with all HTML elements. In our case we are updating a div every time a query is sent off. Also, remember that you can easily access an HTML element by giving it an id and using Javascript's document.getElementById function.
If you have successfully completed this advanced Ajax lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.

0 comments:

Post a Comment

 
  • Symbolic Constants

    What Is The Variables and Arithmetic Expressions The next program uses the formula oC=(5/9)(oF-32) to print the following table

  • Navigation For Blogger New Script

    Today we will see how to add a nice page number navigation hack blogger. The default navigation links (i.e Older Posts) is not the friend

  • How To Creat Facebook Fantasty Box

    Fantasty Look Custom Facebook Like Box To Blogger Facebook Like Box is very useful widget to show visitors the authority and love of t

  • Basic Knowladge Of Computer

    Computer is an electronic device that accepts the data from any Input Device process them according to instruction and gives the Output.Computer is an electronic device that..

  • Earn Money To Easy Way

    HI MEMBER, FIRST OF ALL HEARTY WELCOME TO OUR COMPANY.FIRST TIME IN THE WORLD WE ARE INTRODUCING A STEP BY STEP TRAINING PROCESS TO MAKE MONEYMAKE MONEY ONLINE

Top
Blogger Template - See more at: http://www.arya2014.blogspot.in
ONLINE EDUCATION Basic Computer Application EARN MONEY TO EASY WAY Make Money Online "C" PROGRAMING Introducing "C" Language