AJAX: Getting StartedFrom MDCMain Page> AJAX> Getting Started
This article guides you through the AJAX basics and gives you two simple hands-on examples to get you started.
Contents [Hide]
- 1 What's AJAX?
- 2 Step 1-say "Please! "Or How to Make an HTTP Request
- 3 Step 2-"There you go! "Or Handling the Server Response
- 4 Step 3-"All together now! "-A Simple Example
- 5 Step 4-"The X-Files" or Working with the XML Response
|
[Edit]
What's AJAX?
AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been und for years, but were overlooked by your web developers until recently when applications such as Gmail, google suggest, and Google Maps hit the streets.
The two features in question are that you can:
- Make requests to the server without reloading the page
- Parse and work with XML documents ents
[Edit]
Step 1-say "Please! "Or How to Make an HTTP Request
In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides you this functionality. such a class was originally introduced in Internet Explorer as an ActiveX object, calledXMLHTTP
. Then Mozilla, Safari and other browsers followed, implementingXMLHttpRequest
Class that supports the methods and properties of Microsoft's original ActiveX object.
As a result, in order to create a cross-browser instance (object) of the required class, you can do:
if (window.XMLHttpRequest) { // Mozilla, Safari, ... http_request = new XMLHttpRequest();} else if (window.ActiveXObject) { // IE http_request = new ActiveXObject("Microsoft.XMLHTTP");}
(For authentication purposes, the above is a bit simplified version of the code to be used for creating an XMLHTTP instance. For a more real-life example, see step 3 of this article .)
Some versions of some Mozilla browsers won't work properly if the response from the server doesn' t have an XML mime-type header. to satisfy this, you can use an extra method call to override the header sent by the server, just in case it's nottext/xml
.
http_request = new XMLHttpRequest();http_request.overrideMimeType('text/xml');
The next thing is to decide what you want to do after you receive the server response to your request. at this stage you just need to tell the HTTP request object which JavaScript function will do the work of processing the response. this is done by settingonreadystatechange
Property of the object to the name of the JavaScript function you plan to use, like this:
http_request.onreadystatechange = nameOfTheFunction;
Note that there are no brackets after the function name and no parameters passed. also, instead of giving a function name, you can use the Javascript technique of defining functions on the fly and define the actions that will process the response right away, like this:
http_request.onreadystatechange = function(){ // do the thing};
Next, after you 've declared what will happen as soon as you receive the response, you need to actually make the request. You need to callopen()
Andsend()
Methods of the HTTP request class, like this:
http_request.open('GET', 'http://www.example.org/some.file', true);http_request.send(null);
- The first parameter of the call
open()
Is the HTTP request method-GET, POST, HEAD or any other method you want to use and that is supported by your server. keep the method capitalized as per the HTTP standard; otherwise some browsers (like Firefox) might not process the request. for more information on the possible HTTP request methods you can check the W3C specs
- The second parameter is the URL of the page you're requesting. as a security feature, you cannot call pages on 3rd-party domains. be sure to use the exact domain name on all of your pages or you will get a 'permission denied 'error when you call open (). A common pitfall is accessing your site by domain. tld, but attempting to call pages with www. domain. tld.
- The third parameter sets whether the request is asynchronous. If
TRUE
, The execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the in AJAX.
The parameter tosend()
Method can be any data you want to send to the server if POST-ing the request. The data shocould be in the form of a query string, like:
name=value&anothername=othervalue&so=on
Note that if you want to POST data, you have to change the MIME type of the request using the following line:
http_request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Otherwise, the server will discard the POSTed data.
[Edit]
Step 2-"There you go! "Or Handling the Server Response
Remember that when you were sending the request, you provide the name of a JavaScript function that is designed to handle the response.
http_request.onreadystatechange = nameOfTheFunction;
Let's see what this function shoshould do. first, the function needs to check for the state of the request. if the state has the value of 4, that means that the full server response is already ed and it's OK for you to continue processing it.
if (http_request.readyState == 4) { // everything is good, the response is received} else { // still not ready}
The full list ofreadyState
Values is as follows:
- 0 (uninitialized)
- 1 (loading)
- 2 (loaded)
- 3 (interactive)
- 4 (complete)
(Source)
The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the W3C site. For our purposes we are only interested in200 OK
Response.
if (http_request.status == 200) { // perfect!} else { // there was a problem with the request, // for example the response may be a 404 (Not Found) // or 500 (Internal Server Error) response codes}
Now after you 've checked the state of the request and the HTTP status code of the response, it's up to you to do whatever you want with the data the server has sent to you. you have two options to access that data:
http_request.responseText
-Will return the server response as a string of text
http_request.responseXML
-Will return the response asXMLDocument
Object you can traverse using the JavaScript DOM functions
[Edit]
Step 3-"All together now! "-A Simple Example
Let's put it all together and do a simple HTTP request. Our JavaScript will request an HTML document,test.html
, Which contains the text "I'm a test." and then we'llalert()
The contents oftest.html
File.
<script type="text/javascript" language="javascript"> function makeRequest(url) { var http_request = false; if (window.XMLHttpRequest) { // Mozilla, Safari,... http_request = new XMLHttpRequest(); if (http_request.overrideMimeType) { http_request.overrideMimeType('text/xml'); // See note below about this line } } else if (window.ActiveXObject) { // IE try { http_request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { http_request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} } } if (!http_request) { alert('Giving up :( Cannot create an XMLHTTP instance'); return false; } http_request.onreadystatechange = function() { alertContents(http_request); }; http_request.open('GET', url, true); http_request.send(null); } function alertContents(http_request) { if (http_request.readyState == 4) { if (http_request.status == 200) { alert(http_request.responseText); } else { alert('There was a problem with the request.'); } } }</script><span style="cursor: pointer; text-decoration: underline" onclick="makeRequest('test.html')"> Make a request</span>
In this example:
- The user clicks the link "Make a request" in the browser;
- This callthe
makeRequest()
Function with a parameter-the nametest.html
Of an HTML file in the same directory;
- The request is made and then (
onreadystatechange
) The execution is passedalertContents()
;
alertContents()
Checks if the response was stored Ed and it's an OK and thenalert()
S the contents oftest.html
File.
You can test the example here and you can see the test file here.
Note: The linehttp_request.overrideMimeType('text/xml');
Will ababove cause Javascript Console errors in Firefox 1.5b as your ented at https://bugzilla.mozilla.org/show_bug.cgi? Id = 311724 if the page called by XMLHttpRequest is not valid XML (eg, if it is plain text ).
If you get Syntax Error or Not Well Formed Error on that browser, and you're not trying to load an XML page from XMLHttpRequest, remove that line from your code.
Note 2: If you are sending a request to a piece of code that will return XML, rather than to a static XML file, you must set some response headers if your page is to work in Internet Explorer in addition to Mozilla. if you do not set headerContent-Type: application/xml
, IE will throw a Javascript error 'object exists' after the line where you try to access an XML element. If you do not set headerCache-Control: no-cache
The browser will cache the response and never re-submit the request, making debugging 'challenging '.
Note 3: If the http_request variable is used globally, competing functions calling makeRequest () may overwrite each other, causing a race condition. declaring the http_request variable local to the function and passing it to the alertContent () function prevents the race condition.
Note 4: To register the call back function onreadystatechange, you cannot have any argument:
http_request.onreadystatechange = function() { alertContents(http_request); }; //1 (simultaneous request)http_request.onreadystatechange = alertContents(http_request); //2 (does not work)http_request.onreadystatechange = alertContents; //3 (global variable)
Method 1 allows to have several requests done in simultaneously, method 2 will not work, method 3 is used if http_request is a global variable
[Edit]
Step 4-"The X-Files" or Working with the XML Response
In the previous example, after the response to the HTTP request was encoded Ed, we usedreponseText
Property of the request object and it contained the contents oftest.html
File. Now let's tryresponseXML
Property.
First off, let's create a valid XML document that we'll request later on. The document (test. xml) contains the following:
<?xml version="1.0" ?><root> I'm a test.</root>
In the script we only need to change the request line:
...onclick="makeRequest('test.xml')">...
Then inalertContents()
We need to replacealert()
-Ing linealert(http_request.responseText);
With:
var xmldoc = http_request.responseXML;var root_node = xmldoc.getElementsByTagName('root').item(0);alert(root_node.firstChild.data);
This way we tookXMLDocument
Object givenresponseXML
And we used DOM methods to access some data contained in the XML document. You can seetest.xml
Here and the updated test script here.
For more on the DOM methods, be sure to check Mozilla's DOM implementation statements.
Retrieved from "http://developer.mozilla.org/en/docs/AJAX:Getting_Started"
Categories: AJAX: Getting Started | AJAX: Articles
- This page was last modified 12: 08, 24 February 2006.
- This page has been accessed 217,609 times.
- Content is available under these licenses.
- About MDC