Archive for August, 2008

Getting Started: Ajax

August 30th, 2008 by admin
  

 

Getting Started: Ajax

The foundation that makes Ajax possible is the communication layer
with the server. The most complete option for performing this
communication is the JavaScript XMLHttpRequest object. If XMLHttpRequest is not suitable to you, hidden IFrames and cookies can also be used. We will examine both options later in this chapter.

This chapter introduces you to the XMLHttpRequest
object, showing you how to work around its implementation differences
between browsers. After that, we make some actual page requests, both
in a synchronous fashion and in an asynchronous fashion. This chapter
finishes with some various fallback approaches that can be used if a
browser doesn’t support XMLHttpRequest, including how to use IFrames and cookies as your communication channel.

2.1 XMLHttpRequest Overview

Originally, Microsoft designed XMLHttpRequest to allow Internet Explorer (IE) to load XML documents from JavaScript. Even though it has XML in its name, XMLHttpRequest really is a generic HTTP client for JavaScript. With it, JavaScript can make GET and POST HTTP requests. (For POST requests, data can be sent to the server in a format of your choosing.) The main limitations to XMLHttpRequest
are due to the browser security sandbox. It can make only HTTP(S)
requests (file URLs, for example, won’t work), and it can make requests
only to the same domain as the currently loaded page.

The security limitations of XMLHttpRequest do limit
the ways in which you can use it, but the trade-off in added security
is well worth it. Most attacks against JavaScript applications center
around injecting malicious code into the Web page. If XMLHttpRequest
allowed requests to any Web site, it would become a major player in
these attacks. The security sandbox reduces these potential problems.
In addition, it simplifies the programming model because the JavaScript
code can implicitly trust any data it loads from XMLHttpRequest. It can trust the data because the new data is just as secure as the page that loaded the initial page.

Despite the fact that XMLHttpRequest provides only a
small API and just a handful of methods and properties, it has its
differences between browsers. These differences are mainly in event
handling and object instantiation (in IE, XMLHttpRequest is actually an ActiveX object), so they aren’t hard to work around. In the following overview of the XMLHttpRequest API, the Mozilla syntax for XMLHttpRequest instantiation is used. If you want to run the examples in IE, you need to replace new XMLHttpRequest(); with either new ActiveXObject("MSXML2.XMLHTTP.3.0"); or the full cross-browser instantiation method shown in the “Cross-Browser XMLHttpRequest” section of this chapter.

XMLHttpRequest is the most-used method for Ajax
communications because it provides two unique features. The first
feature provides the ability to load new content without that content
being changed in any way, which makes it extremely easy to fit Ajax
into your normal development patterns. The second feature allows
JavaScript to make synchronous calls. A synchronous call stops all
other operations until it’s complete, and while this isn’t an option
that is usually used, it can be useful in cases in which the current
request must be completed before further actions are taken.

2.1.1 XMLHttpRequest::Open()

The open method is used to set the request type (GET, POST, PUT, or PROPFIND),
the URL of the page being requested, and whether the call will be
asynchronous. A username and password for HTTP authentication can also
be optionally passed. The URL can be either a relative path (such as page.html) or a complete one that includes the server’s address (such as http://www.expertzweb.com). The basic method signature is:

open(type,url,isAsync,username,password)

In the JavaScript environment, security restrictions are in place. These security restrictions cause the open method to throw an exception if the URL is from a different domain than the current page. The following example uses open to set up a synchronous GET request to index.html:

1 var req = new XMLHttpRequest();
2 req.open(’GET’, ’index.html’, false);
3 req.send(null);
4 if(req.status == 200)
5 alert(req.responseText);

2.1.2 XMLHttpRequest::Send()

The send method makes the connection to the URL specified in open.
If the request is asynchronous, the call will return it immediately;
otherwise, the call will block further execution until the page has
been downloaded. If the request type is POST, the payload will be sent as the body of the request that is sent to the server. The method signature is:


When you make a POST request, you will need to set the Content-type header. This way, the server knows what to do with the uploaded content. To mimic sending a form using HTTP POST, you set the content type to application/x-www-form-urlencoded. URLencoded
data is the same format that you see in a URL after the “?”. You can
see an example of this encoded data by making a form and setting its
method to GET. The following example shows a synchronous POST request to index.php that is sending a URLencoded payload. If index.php contains <?php var_dump($_POST); ?>, you can see the submitted data translated as if it’s a normal form in the alert:

 
1 var req = new XMLHttpRequest(); 
2 req.open(’POST’, ’index.php’, false); 
3 req.setRequestHeader(’Content-type’, 
4      ’application/x-www-form-urlencoded;charset=UTF-8;’); 
5 req.send(’hello=world&XMLHttpRequest=test’); 
6 if(req.status == 200) 
7   alert(req.responseText); 
  view plain | print | ?

2.1.3 XMLHttpRequest::setRequestHeader()

There are many different cases in which setting a header on a request might be useful. The most common use of setRequestHeader() is to set the Content-type, because most Web applications already know how to deal with certain types, such as URLencoded. The setRequestHeader method signature takes two parameters: the header to set and its value:

 
1 setRequestHeader(header,value) 
 

Because requests sent using XMLHttpRequest send the
same standard headers, including cookie headers and HTTP authentication
headers, as a normal browser request, the header name will usually be
the name of the HTTP header that you want to override. In addition to
overriding default headers, setRequestHeader is useful for setting custom, application-specific headers. Custom headers are generally prefixed with X- to distinguish them from standard ones. The following example makes a synchronous GET request adding a header called X-foo to test.php. If test.php contains <?php var_dump($_SERVER); ?>, you will see the submitted header in the alert:

 
1 var req = new XMLHttpRequest(); 
2 req.open(’GET’, ’test.php’, false); 
3 req.setRequestHeader(’X-foo’,’bar’); 
4 req.send(null); 
5  
6 if(req.status == 200) 
7 alert(req.responseText); 
 

2.1.4 XMLHttpRequest::getResponseHeader() and getAllResponseHeaders()

The getResponseHeader method allows you to get a single header from the response; this is especially useful when all you need is a header like Content-type; note that the specified header is case-insensitive. The method signature is as follows:

 
1 getResponseHeader(header) 
 

getAllResponseHeaders returns all the headers from the
response in a single string; this is useful for debugging or searching
for a value. The following example makes a synchronous GET request to test.html. When the client receives a response, the Content-type is alerted and all the headers are alerted:

 
1 var req = new XMLHttpRequest(); 
2 req.open(’GET’, ’test.html’, false); 
3 req.send(null); 
4  
5 if(req.status == 200) { 
6   alert(req.getResponseHeader(’Content-type’)); 
7   alert(req.getAllResponseHeaders()); 
8
 

2.1.5 Other XMLHttpRequest Methods

All browsers implement an abort() method, which is
used to cancel an in-progress asynchronous request. (An example of this
is shown in the “Sending Asynchronous Requests” section in this
chapter.) Mozilla-based browsers also offer some extra methods on top
of the basic API; for instance, addEventListener() and removeEventListener() provide a way to catch status events without using the on* properties. There is also an overrideMimeType() method that makes it possible to force the Content-type to text/xml
so that it will be parsed into a DOM document even if the server
doesn’t report it as such. The Mozilla-specific methods can be useful
in certain circumstances, but in most cases, you should stay away from
them because not all browsers support them.

2.1.6 XMLHttpRequest Properties

XMLHttpRequest provides a number of properties that
provide information or results about the request. Most of the
properties are self-explanatory; you simply read the value and act on
it. The on* properties are event handlers that are used by assigning a function to them. A list of all the properties follows:

  • status. The HTTP status code of the request response.
  • statusText. The HTTP status code that goes with the code.
  • readyState. The state of the request. (See Table 2-1 in the next section of this chapter for values.)
  • responseText. Unparsed text of the response.
  • responseXML. Response parsed into a DOM Document object; happens only if Content-type is text/xml.
  • onreadystatechange. Event handler that is called when readyState changes.
  • onerror. Mozilla-only event handler that is called when an error happens during a request.
  • onprogress. Mozilla-only event handler that is called at an interval as content is loaded.
  • onload. Mozilla-only event handler that is called when the document is finished loading.

2.1.7 readyState Reference

Table 2-1 shows the possible values for the readyState variable. It will return a number representing the current state of the object. Each request will progress through the list of readyStates.

Table 2-1 readyState Levels

readyState Status Code Status of the XMLHttpRequest Object
(0) UNINITIALIZED The object has been created but not initialized. (The open method has not been called.)
(1) LOADING The object has been created, but the send method has not been called.
(2) LOADED The send method has been called, but the status and headers are not yet available.
(3) INTERACTIVE Some data has been received. Calling the responseBody and responseText
properties at this state to obtain partial results will return an
error, because status and response headers are not fully available.
(4) COMPLETED All the data has been received, and the complete data is available in the responseBody and responseText properties.

 

The readyState variable and the onreadystatechange event handler are linked in such a way that each time the readyState variable is changed, the onreadystatechange event handler is called.

2.2 Cross-Browser XMLHttpRequest

One of the attributes that have made XMLHttpRequest
such a popular transport for Ajax requests is that it is easy to use in
a way that is compatible across multiple browsers. The big two
browsers, IE and Firefox, provide the same basic API. This consistency
makes for a similar development experience. Opera and Safari also
support the same basic API, but only in their more recent versions.

When you are writing cross-browser, the first problem you need to overcome is that XMLHttpRequest
is an ActiveX object in IE, and it’s a normal JavaScript object in
Mozilla and the other browsers. There are a number of approaches to
overcoming this problem, including optional JScript code for IE, but I
find that the simplest solution is just to use exceptions. Listing 2-1
shows an example that tries every version of the XMLHTTP
ActiveX object, if needed. This helps make our implementation as robust
as possible. The function also throws an exception if it’s not possible
to create an XMLHttpRequest object. This gives us a way to give error messages or to fall back to IFrame requests, if needed.

Listing 2-1 Cross-Browser XMLHttpRequest Creation

 
1 // function to create an XMLHttpClient in a cross-browser manner 
2 function initXMLHttpClient() { 
3   var xmlhttp; 
4   try { 
5     // Mozilla / Safari / IE7 
6     xmlhttp = new XMLHttpRequest(); 
7   } catch (e) { 
8     // IE 
9     var XMLHTTP_IDS = new Array(’MSXML2.XMLHTTP.5.0’, 
10                   ’MSXML2.XMLHTTP.4.0’, 
11                   ’MSXML2.XMLHTTP.3.0’, 
12                   ’MSXML2.XMLHTTP’, 
13                   ’Microsoft.XMLHTTP’ ); 
14     var success = false
15     for (var i=0;i < XMLHTTP_IDS.length && !success; i++) { 
16       try { 
17       xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]); 
18       success = true
19       } catch (e) {} 
20     } 
21     if (!success) { 
22       throw new Error(’Unable to create XMLHttpRequest.’); 
23     } 
24   } 
25   return xmlhttp; 
26
   

The overall pattern of this code is simple: Create an XMLHttpRequest
instance in the most optimal way possible, as shown in line 6. This
creation should always succeed on Mozilla-based browsers, such as
Firefox, on Opera, and on the upcoming IE 7.

If XMLHttpRequest doesn’t exist, catch the exception
that is thrown, as shown in line 7. Getting an exception means you’re
on IE or an old browser. To test for IE, attempt to create an ActiveX
version of XMLHttpRequest, which is accomplished by the following:

  1. Looping over all possible ActiveX identifiers. This action will
    create an ActiveX instance for each identifier until the creation
    succeeds, setting the success flag to true, as shown in lines 9–20.
  2. If creation is successful, returning an XMLHttpRequest instance, as shown in line 25. Otherwise, throwing a JavaScript exception, as shown in line 22.

This approach allows for minimal overhead if the browser supports a native XMLHttpRequest object while fully supporting IE. It also gives us an error if XMLHttpRequest
isn’t supported at all. This error could be displayed to the user at
this point, or you could insert another communication approach, such as
hidden IFrames.

2.3 Sending Asynchronous Requests

Synchronous requests are easier to use than asynchronous requests
because they return data directly and remove the hassle of creating
callback functions. However, they aren’t the standard use case for XMLHttpRequest
because the entire browser is locked while the request is happening.
There are some circumstances in which blocking is useful (mainly when a
decision needs to be made before the current function ends), but in
most cases, you’ll want these requests to happen in the background. An
asynchronous request allows the browser to continue running JavaScript
code and users to continue interacting with the page while the new data
is loaded. With the proper user interface, asynchronous communication
allows an Ajax application to be useful even when the user’s connection
to the site is slow.

To make an asynchronous call, we need to accomplish two tasks: set the asynchronous flag on open to true, and add a readyStateChanged
event handler. This event handler will wait for a ready state of 4,
which means the response is loaded. It will then check the status
property. If the status is 200, we can use responseText; if it’s another value, we have an error, so we’ll need to create an alert dialog to show it. An asynchronous call to test.php is shown in Listing 2-2. The initXMLHttpClient function from an earlier chapter section, “Cross-Browser XMLHttpRequest,” is used to create our XMLHttpRequest object.

Listing 2-2 Making an Asynchronous Request

 
1 var req = initXMLHttpClient(); 
2 req.onreadystatechange = function() { 
3   if (req.readyState == 4) { 
4     if (req.status == 200) { 
5       alert(req.responseText); 
6     } else { 
7       alert(’Loading Error: [’+req.status+’] ’ 
8          +req.statusText); 
9     } 
10   } 
11
12 req.open(’GET’,’test.php’,true); 
13 req.send(null); 
   

Although this code gets the job done, it’s not a great long-term solution because we will have to write a new onreadystatechange method for each call. The solution to this is to create our own HttpClient class that wraps XMLHttpRequest.
Such a class gives us an easy-to-use API and a property to use for the
callback that has to deal only with successful requests. Just adding
some helper methods would be a simpler solution, but that’s not a
possibility because IE doesn’t allow you to add methods to an ActiveX
object.

A sample XMLHttpRequest wrapper class is shown in Listing 2-3. The main features of the HttpClient class are a callback property that is called when a successful asynchronous request is complete and a makeRequest method that combines the open and send functions. It also provides event properties that are called when a request is made (onSend), when it ends (onload), and when an errors occurs (onError). A default onSend and onLoad implementation is provided, which creates a basic loading message while requests are being made.

Listing 2-3 HttpClient XMLHttpRequest Wrapper

 
1 function HttpClient() { } 
2 HttpClient.prototype = { 
3   // type GET,POST passed to open 
4   requestType:’GET’, 
5   // when set to true, async calls are made 
6   isAsync:false
7  
8   // where an XMLHttpRequest instance is stored 
9   xmlhttp:false
10  
11   // what is called when a successful async call is made 
12   callback:false
13  
14   // what is called when send is called on XMLHttpRequest 
15   // set your own function to onSend to have a custom loading 
16   // effect 
17   onSend:function() { 
18     document.getElementById(’HttpClientStatus’).style.display = 
19                ’block’; 
20   }, 
21  
22   // what is called when readyState 4 is reached, this is 
23   // called before your callback 
24   onload:function() { 
25     document.getElementById(’HttpClientStatus’).style.display = 
26                ’none’; 
27   }, 
28  
29   // what is called when an http error happens 
30   onError:function(error) { 
31     alert(error); 
32   }, 
33  
34   // method to initialize an xmlhttpclient 
35   init:function() { 
36     try { 
37       // Mozilla / Safari 
38       this.xmlhttp = new XMLHttpRequest(); 
39     } catch (e) { 
40       // IE 
41       var XMLHTTP_IDS = new Array(-’MSXML2.XMLHTTP.5.0’, 
42                    -’MSXML2.XMLHTTP.4.0’, 
43                    ’MSXML2.XMLHTTP.3.0’, 
44                    ’MSXML2.XMLHTTP’, 
45                    -’Microsoft.XMLHTTP’); 
46       var success = false
47       -for (var i=0;i < XMLHTTP_IDS.length && !success; i++) { 
48         try { 
49           -this.xmlhttp = new ActiveXObject(XMLHTTP_IDS[i]); 
50           success = true
51         } catch (e) {} 
52       -} 
53       -if (!success) { 
54         -this.onError(’Unable to create XMLHttpRequest.’); 
55       } 
56     } 
57   }, 
58  
59   // method to make a page request 
60   // @param string url The page to make the request to 
61   // @param string payload What you’re sending if this is a POST 
62   //            request 
63   makeRequest: function(url,payload) { 
64    if (!this.xmlhttp) { 
65      this.init(); 
66    } 
67    this.xmlhttp.open(this.requestType,url,this.isAsync); 
68  
69    -// set onreadystatechange here since it will be reset after a 
70    //completed call in Mozilla 
71    var self = this
72    this.xmlhttp.onreadystatechange = function() { 
73    self._readyStateChangeCallback(); } 
74  
75    this.xmlhttp.send(payload); 
76  
77    if (!this.isAsync) { 
78      return this.xmlhttp.responseText; 
79    } 
80 }, 
81  
82 // internal method used to handle ready state changes 
83 _readyStateChangeCallback:function() { 
84     switch(this.xmlhttp.readyState) { 
85      case 2: 
86        this.onSend(); 
87        break
88      case 4: 
89        this.onload(); 
90        if (this.xmlhttp.status == 200) { 
91          this.callback(this.xmlhttp.responseText); 
92        } else { 
93          -this.onError(’HTTP Error Making Request: ’+ 
94                    -’[’+this.xmlhttp.status+’]’+ 
95                    -’+this.xmlhttp.statusText)); 
96        } 
97        break
98     } 
99   } 
100
 

The HttpClient class contains comments explaining its
basic functionality, but you will want to look at a couple of areas in
detail. The first areas are the properties you’ll want to set while
interacting with the class; these include the following:

  • requestType (line 4). Used to set the HTTP request type, GET is used to request content that doesn’t perform an action whereas POST is used for requests that do.
  • isAsync (line 6). A
    Boolean value used to set the request method. The default is false,
    which makes an synchronous request. If you’re making an asynchronous
    request, isAsync is set to true. When making an asynchronous request, you also need to set the callback property.
  • callback (line 12). This property takes a function that takes a single parameter result and is called when a request is successfully completed.

Lines 16–31 contain simple functions for handling some basic user
feedback. When a request is sent to the server, a DOM element with the
ID of HttpClientStatus
is shown (lines 16–19). When it completes, it is hidden again (lines
23–26). The class also defines a function to call when an error happens
(lines 29–31); it creates an alert box with the error message. Common
errors include receiving a 404 page not found HTTP error message or not being able to create an XMLHttpRequest
object. The implementation of these three functions is simple, and
you’ll likely want to override them with more sophisticated
application-specific versions.

Lines 33–56 contain the init method, which is identical to the initXMLHttpClient function we created in Listing 2-1, except for what it does with its error message. Now it sends it to the onError method. You won’t be dealing with this function directly because the makeRequest method will take care of it for you. The makeRequest
method (lines 62–79) is your main interaction with the class. It takes
two parameters: a URL to which to make the request and a payload that
is sent to the server if you’re making a POST request. The actual implementation is a more generic version of the code shown in Listing 2-2. The _readyStateChangeCallback (lines 82–99) method is set as the readyState handler by makeRequest. It handles calling onSend when the initial request is sent and then calling onload when the request completes. It also checks for a 200 HTTP status code and calls onError if some other status is returned.

Listing 2-4 uses the HttpClient class and shows its
basic usage. A wrapper class like this helps cut down the amount of
code you need to write per request while giving a single place to make
future changes.

Listing 2-4 Using the HttpClient XMLHttpRequest Wrapper

 
1 <html> 
2 <head> 
3 <title>Simple XMLHttpRequest Wrapper Test Page</title> 
4  
5 <script type=“text/javascript” src=“HttpClient.js”></script> 
6 <body> 
7 <script type=“text/javascript”
8  
9 var client = new HttpClient(); 
10 client.isAsync = true
11  
12 function test() { 
13   client.callback = function(result) { 
14     document.getElementById(’target’).innerHTML = result; 
15   } 
16   client.makeRequest(’.’,null); 
17
18 </script> 
19  
20 <div id=“HttpClientStatus” style=“display:none”>Loading …</div> 
21 <a href=’javascript:test()’>Make an Async Test call</a> 
22 <div id=“target”></div> 
23 </body> 
24 </html> 
   

Using the HttpClient XMLHttpRequest wrapper is a
simple task. You start by including it in the header of your HTML page
(line 5), and then you can proceed to use it. You do this by creating
an instance of the class (line 9), configuring its basic properties (in
this case, setting isAsync to true (line 10)), and then setting up some code to call makeRequest.
In most cases, this code will be contained in a function so that it can
be tied to a user-driven event, such as clicking a link. The call is
made by the test function (lines 12–17); the test function first sets up a callback to run when the request is complete (lines 13–15), and then it calls makeRequest (line 16), which starts the Ajax call.

2.4 Ajax Without XMLHttpRequest

There are a number of cases in which you might not have XMLHttpRequest
support. The most common would be in the case of an older browser. This
is the hardest to work around, not because there is no Ajax fallback,
but because all the other DOM manipulation that you do within the
application won’t work. Another problem case is when your browser
supports everything that is needed except for XMLHttpRequest. This problem could occur when IE is in a mode where it can’t use ActiveXObjects
or when you are using a pre-7.6 version of Opera. In some cases,
especially intranet applications, it’s easy to just require an upgrade,
but if you want to use Ajax on a public site, you’ll want to think
about using some sort of fallback mechanism. The best candidate for a
fallback is to use hidden IFrames. Another option is to
use cookies, but they can send only a limited amount of data per
request, so it is hard to drop in cookie-based approaches as a
replacement for code that has been written with XMLHttpRequest in mind. Only XMLHttpRequest supports synchronous calls, so if they are necessary for your application, then using it as a fallback will not be possible.

If you’re using a fully wrapped XMLHttpRequest and
you don’t use synchronous calls, providing transparent fallback to your
program should be possible. You need only to replace the final throwing
of an exception in the example init method with the instantiation of your IFrame HTTP client. The main item to remember about using another approach instead of XMLHttpRequest is that it’s not going to gain you huge leaps in compatibility. The major browsers already support XMLHttpRequest.
This support makes browsers with JavaScript turned off, not those
running an unsupported browser, the biggest group that can’t use your
Ajax application. The advantages and disadvantages of the Ajax
communication techniques are shown in Table 2-2.

Table 2-2 Advantages and Disadvantages of Ajax Techniques

Technique Advantages Disadvantages
XMLHttpRequest Can make requests to pages not set up for Ajax 

Can set/get all HTTP headers

Can make HTTP requests using any type (GET, POST, PROPFIND, and so on)

Supports full control over POST requests, allowing for any type of data encoding

Requests ActiveX to be enabled in IE 5 and 6

Is only available in newer versions of Opera and Safari 

Has small implementation differences between browsers

IFrame Can make POST and GET HTTP requests 

Supportes all modern browsers

Supports asynchronous file uploads

Prohibits synchronous requests 

Server pages must be designed to work with IFrame requests

Has implementation differences between browsers

Can leave extra entries in browser history (depends on browser and implementation)

All request data is URL-encoded, increasing request size

Cookies Supports the largest number of browsers 

Few implementation differences between browsers

Prohibits no synchronous requests

Doesn’t work with large requests/results 

Requires server pages to be designed to work with cookie requests

Requires polling on the client

Can make only GET HTTP requests

 

Tags: , , ,

AJAX and Database PHP

August 30th, 2008 by admin

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 “ajax.html”. But before we proceed, lets do ground work. Create a table using the following command.

NOTE: We are asuing you have sufficient privilege to perform following MySQL operations

CREATE TABLE `ajax_example` (
  `name` varchar(50) NOT NULL,
  `age` int(11) NOT NULL,
  `sex` varchar(1) NOT NULL,
  `wpm` int(11) NOT NULL,
  PRIMARY KEY  (`name`)
)

Now dump the following data into this table using the following SQL statements

INSERT INTO `ajax_example` VALUES ('Jerry', 120, 'm', 20);
INSERT INTO `ajax_example` VALUES ('Regis', 75, 'm', 44);
INSERT INTO `ajax_example` VALUES ('Frank', 45, 'm', 87);
INSERT INTO `ajax_example` VALUES ('Jill', 22, 'f', 72);
INSERT INTO `ajax_example` VALUES ('Tracy', 27, 'f', 0);
INSERT INTO `ajax_example` VALUES ('Julie', 35, 'f', 90);

Client Side HTML file

Now lets have our client side HTML file which is ajax.html and it will have following code

<html>
<body>
<script language="javascript" type="text/javascript">
<!-- 

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 and will update
 // div section in the same page.
 ajaxRequest.onreadystatechange = function(){
   if(ajaxRequest.readyState == 4){
      var ajaxDisplay = document.getElementById('ajaxDiv');
      ajaxDisplay.value = ajaxRequest.responseText;
   }
 }
 // Now get the value from user and pass it to
 // server script.
 var age = document.getElementById('age').value;
 var wpm = document.getElementById('wpm').value;
 var sex = document.getElementById('sex').value;
 var queryString = "?age=" + age ;
 queryString +=  "&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>

NOTE: The way of passing variables in the Query is according to HTTP standard and the have formA

URL?variable1=value1;&variable2=value2;

Now the above code will give you a screen as given below


NOTE: This is dummy screen and would not work

 

Max Age:  

Max WPM: 

Sex: 

 

 

Your result will display here

 


Server Side PHP file

So now your client side script is ready. Now we have to write our server side script which will fetch age, wpm and sex from the database and will send it back to the client. Put the following code into “ajax-example.php” file

<?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 sex = '$sex'";
if(is_numeric($age))
	$query .= " AND age <= $age";
if(is_numeric($wpm))
	$query .= " AND 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[name]</td>";
	$display_string .= "<td>$row[age]</td>";
	$display_string .= "<td>$row[sex]</td>";
	$display_string .= "<td>$row[wpm]</td>";
	$display_string .= "</tr>";

}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";
echo $display_string;
?>

 

 

If you have successfully completed this lesson then you know how to use MySQL, PHP, HTML, and Javascript in tandem to write Ajax applications.