Getting Started

  • Revision slug: AJAX/Getting_Started
  • Revision title: Getting Started
  • Revision id: 48796
  • Created:
  • Creator: De saint
  • Is current revision? No
  • Comment

Revision Content

This article guides you through the AJAX basics and gives you two simple hands-on examples to get you started.

What's AJAX? for Alex de Sain

Ajax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the nonstandard XMLHttpRequest object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including XML, HTML, and even text files. Ajax’s most appealing characteristic, however, is its “asynchronous” nature, which means it can do all of this without having to refresh the page. This allows you to update portions of a page based upon user events.

The two features in question are that you can:

  • Make requests to the server without reloading the page
  • Parse and work with XML documents

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 this functionality. Such a class was originally introduced in Internet Explorer as an ActiveX object, called XMLHTTP. Then Mozilla, Safari and other browsers followed, implementing an XMLHttpRequest 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:

var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}

(For illustration 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 not text/xml.

httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');

Next, you need 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 setting the onreadystatechange property of the object to the name of the JavaScript function you plan to use, like this:

httpRequest.onreadystatechange = nameOfTheFunction;

Note that there are no brackets after the function name and no parameters passed, because you're simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous function") and define the actions that will process the response right away, like this:

httpRequest.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 call the open() and send() methods of the HTTP request class, like this:

httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send(null);
  • The first parameter of the call to 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 <tt>domain.tld</tt>, but attempting to call pages with <tt>www.domain.tld</tt>.
  • 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 A in AJAX.

The parameter to the send() method can be any data you want to send to the server if POST-ing the request. The data should 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:

httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

Otherwise, the server will discard the POSTed data.

Step 2 – "There you go!" or Handling the Server Response

Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response.

httpRequest.onreadystatechange = nameOfTheFunction;

Let's see what this function should 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 received and it's OK for you to continue processing it.

if (httpRequest.readyState == 4) {
    // everything is good, the response is received
} else {
    // still not ready
}

The full list of the readyState 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 in 200 OK response.

if (httpRequest.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:

  • httpRequest.responseText – will return the server response as a string of text
  • httpRequest.responseXML – will return the response as an XMLDocument object you can traverse using the JavaScript DOM functions

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'll alert() the contents of the test.html file.

<script type="text/javascript" language="javascript">
    function makeRequest(url) {
        var httpRequest;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
                // See note below about this line
            }
        } 
        else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (e) {
                           try {
                                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                               } 
                             catch (e) {}
                          }
                                       }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
        httpRequest.open('GET', url, true);
        httpRequest.send('');

    }

    function alertContents(httpRequest) {

        if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
                alert(httpRequest.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 calls the makeRequest() function with a parameter – the name test.html of an HTML file in the same directory;
  • The request is made and then (onreadystatechange) the execution is passed to alertContents();
  • alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file.

Note: The line httpRequest.overrideMimeType('text/xml'); above will cause JavaScript Console errors in Firefox 1.5 or later, as documented in {{template.Bug(311724)}} if the page retrieve by XMLHttpRequest is not valid XML (e.g., if it is plain text). This is actually correct behavior; this article will be revised soon to address this change.

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 header Content-Type: application/xml, IE will throw a JavaScript error, 'Object Expected', after the line where you try to access an XML element. If you do not set header Cache-Control: no-cache the browser will cache the response and never re-submit the request, making debugging "challenging."

Note 3: if the httpRequest variable is used globally, competing functions calling makeRequest() may overwrite each other, causing a race condition. Declaring the httpRequest variable local to the function and passing it to the alertContent() function prevents the race condition.

Note 4: To register the callback function onreadystatechange, you cannot have any arguments. That's why the following code does not work:

httpRequest.onreadystatechange = alertContents(httpRequest); // (does not work)

So, to register the function successfully, you can either pass the arguments indirectly via the anonymous function or use httpRequest as a global variable. Examples follow:

httpRequest.onreadystatechange = function() { alertContents(httpRequest); };  //1 (simultaneous request)
httpRequest.onreadystatechange = alertContents;  //2 (global variable)

Method 1 lets you have several requests processed simultaneously, while method 2 is used if httpRequest is a global variable.


Note 5: In the event of a communication error (such as the webserver going down), an exception will be thrown in the onreadystatechange method when attempting to access the .status variable. Make sure that you wrap your if...then statement in a try...catch. (See: {{template.Bug(238559)}}).

function alertContents(httpRequest) {

        try {
            if (httpRequest.readyState == 4) {
                if (httpRequest.status == 200) {
                    alert(httpRequest.responseText);
                } else {
                    alert('There was a problem with the request.');
                }
            }
        }
        catch( e ) {
            alert('Caught Exception: ' + e.description);
        }

    }

Step 4 – "The X-Files" or Working with the XML Response

In the previous example, after the response to the HTTP request was received we used the responseText property of the request object, which contained the contents of the <tt>test.html</tt> file. Now let's try the responseXML property.

First off, let's create a valid XML document that we'll request later on. The document (<tt>test.xml</tt>) contains the following:

<?xml version="1.0" ?>
<root>
    I'm a test.
</root>

In the script we only need to change the request line to:

...
onclick="makeRequest('test.xml')">
...

Then in alertContents(), we need to replace the line alert(httpRequest.responseText); with:

var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);

This code takes the XMLDocument object given by responseXML and uses DOM methods to access some of the data contained in the XML document. You can see the test.xml here and the updated test script here.

For more on DOM methods, be sure to check Mozilla's DOM implementation documents.

{{ wiki.languages( { "ca": "ca/AJAX/Primers_passos", "de": "de/AJAX/Getting_Started", "es": "es/AJAX/Primeros_Pasos", "fr": "fr/AJAX/Premiers_pas", "it": "it/AJAX/Iniziare", "ja": "ja/AJAX/Getting_Started", "ko": "ko/AJAX/Getting_Started", "pl": "pl/AJAX/Na_pocz\u0105tek", "pt": "pt/AJAX/Como_come\u00e7ar", "zh-cn": "cn/AJAX/\u5f00\u59cb", "ru": "ru/AJAX/\u0421_\u0447\u0435\u0433\u043e_\u043d\u0430\u0447\u0430\u0442\u044c" } ) }}

Revision Source

<p>
This article guides you through the AJAX basics and gives you two simple hands-on examples to get you started.
</p>
<h3 name="What.27s_AJAX.3F_for_Alex_de_Sain"> What's AJAX? for Alex de Sain</h3>
<p>Ajax stands for Asynchronous JavaScript and XML. In a nutshell, it is the use of the nonstandard <code><a href="en/XMLHttpRequest">XMLHttpRequest</a></code> object to communicate with server-side scripts. It can send as well as receive information in a variety of formats, including XML, HTML, and even text files. Ajax’s most appealing characteristic, however, is its “asynchronous” nature, which means it can do all of this without having to refresh the page. This allows you to update portions of a page based upon user events.
</p><p>The two features in question are that you can:
</p>
<ul><li> Make requests to the server without reloading the page
</li><li> Parse and work with XML documents
</li></ul>
<h3 name="Step_1_.E2.80.93_say_.22Please.21.22_or_How_to_Make_an_HTTP_Request"> Step 1 – say "Please!" or How to Make an HTTP Request </h3>
<p>In order to make an HTTP request to the server using JavaScript, you need an instance of a class that provides this functionality. Such a class was originally introduced in Internet Explorer as an ActiveX object, called <code>XMLHTTP</code>. Then Mozilla, Safari and other browsers followed, implementing an <code>XMLHttpRequest</code> class that supports the methods and properties of Microsoft's original ActiveX object.
</p><p>As a result, in order to create a cross-browser instance (object) of the required class, you can do:
</p>
<pre>var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
</pre>
<p>(For illustration 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.)
</p><p>Some versions of some Mozilla browsers won't work properly if the response from the server doesn't have an XML <code>mime-type</code> header. To satisfy this, you can use an extra method call to override the header sent by the server, just in case it's not <code>text/xml</code>.
</p>
<pre>httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');
</pre>
<p>Next, you need 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 setting the <code>onreadystatechange</code> property of the object to the name of the JavaScript function you plan to use, like this:
</p><p><code>httpRequest.onreadystatechange = nameOfTheFunction;</code>
</p><p>Note that there are no brackets after the function name and no parameters passed, because you're simply assigning a reference to the function, rather than actually calling it. Also, instead of giving a function name, you can use the JavaScript technique of defining functions on the fly (called "anonymous function") and define the actions that will process the response right away, like this:
</p>
<pre>httpRequest.onreadystatechange = function(){
    // do the thing
};
</pre>
<p>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 call the <code>open()</code> and <code>send()</code> methods of the HTTP request class, like this:
</p>
<pre>httpRequest.open('GET', 'http://www.example.org/some.file', true);
httpRequest.send(null);
</pre>
<ul><li> The first parameter of the call to <code>open()</code> 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 <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html">W3C specs</a> 
</li><li> 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 <code>open()</code>. A common pitfall is accessing your site by <tt>domain.tld</tt>, but attempting to call pages with <tt>www.domain.tld</tt>.
</li><li> The third parameter sets whether the request is asynchronous. If <code>TRUE</code>, the execution of the JavaScript function will continue while the response of the server has not yet arrived. This is the A in AJAX.
</li></ul>
<p>The parameter to the <code>send()</code> method can be any data you want to send to the server if <code>POST</code>-ing the request. The data should be in the form of a query string, like:
</p><p><code>name=value&amp;anothername=othervalue&amp;so=on</code>
</p><p>Note that if you want to <code>POST</code> data, you have to change the MIME type of the request using the following line:
</p>
<pre>httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
</pre>
<p>Otherwise, the server will discard the <code>POST</code>ed data.
</p>
<h3 name="Step_2_.E2.80.93_.22There_you_go.21.22_or_Handling_the_Server_Response"> Step 2 – "There you go!" or Handling the Server Response </h3>
<p>Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response. 
</p>
<pre class="eval">httpRequest.onreadystatechange = <i>nameOfTheFunction</i>;
</pre>
<p>Let's see what this function should 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 received and it's OK for you to continue processing it. 
</p>
<pre>if (httpRequest.readyState == 4) {
    // everything is good, the response is received
} else {
    // still not ready
}
</pre>
<p>The full list of the <code>readyState</code> values is as follows:
</p>
<ul><li> 0 (uninitialized)
</li><li> 1 (loading)
</li><li> 2 (loaded)
</li><li> 3 (interactive)
</li><li> 4 (complete)
</li></ul>
<p>(<a class="external" href="http://msdn.microsoft.com/workshop/author/dhtml/reference/properties/readystate_1.asp">Source</a>)
</p><p>The next thing to check is the status code of the HTTP server response. All the possible codes are listed on the <a class="external" href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html">W3C site</a>. For our purposes we are only interested in <code>200 OK</code> response.
</p>
<pre>if (httpRequest.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
}
</pre>
<p>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:
</p>
<ul><li> <code>httpRequest.responseText</code> – will return the server response as a string of text
</li><li> <code>httpRequest.responseXML</code> – will return the response as an <code>XMLDocument</code> object you can traverse using the JavaScript DOM functions
</li></ul>
<h3 name="Step_3_.E2.80.93_.22All_together_now.21.22_-_A_Simple_Example"> Step 3 – "All together now!" - A Simple Example </h3>
<p>Let's put it all together and do a simple HTTP request. Our JavaScript will request an HTML document, <code>test.html</code>, which contains the text "I'm a test." and then we'll <code>alert()</code> the contents of the <code>test.html</code> file.
</p>
<pre>&lt;script type="text/javascript" language="javascript"&gt;
    function makeRequest(url) {
        var httpRequest;

        if (window.XMLHttpRequest) { // Mozilla, Safari, ...
            httpRequest = new XMLHttpRequest();
            if (httpRequest.overrideMimeType) {
                httpRequest.overrideMimeType('text/xml');
                // See note below about this line
            }
        } 
        else if (window.ActiveXObject) { // IE
            try {
                httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                } 
                catch (e) {
                           try {
                                httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                               } 
                             catch (e) {}
                          }
                                       }

        if (!httpRequest) {
            alert('Giving up :( Cannot create an XMLHTTP instance');
            return false;
        }
        httpRequest.onreadystatechange = function() { alertContents(httpRequest); };
        httpRequest.open('GET', url, true);
        httpRequest.send('');

    }

    function alertContents(httpRequest) {

        if (httpRequest.readyState == 4) {
            if (httpRequest.status == 200) {
                alert(httpRequest.responseText);
            } else {
                alert('There was a problem with the request.');
            }
        }

    }
&lt;/script&gt;
&lt;span
    style="cursor: pointer; text-decoration: underline"
    onclick="makeRequest('test.html')"&gt;
        Make a request
&lt;/span&gt;
</pre>
<p><br>
In this example:
</p>
<ul><li> The user clicks the link "Make a request" in the browser;
</li><li> This calls the <code>makeRequest()</code> function with a parameter – the name <code>test.html</code> of an HTML file in the same directory;
</li><li> The request is made and then (<code>onreadystatechange</code>) the execution is passed to <code>alertContents()</code>;
</li><li> <code>alertContents()</code> checks if the response was received and it's an OK and then <code>alert()</code>s the contents of the <code>test.html</code> file.
</li></ul>
<p><b>Note</b>: The line <code>httpRequest.overrideMimeType('text/xml');</code> above will cause JavaScript Console errors in Firefox 1.5 or later, as documented in {{template.Bug(311724)}} if the page retrieve by XMLHttpRequest is not valid XML (e.g., if it is plain text).  This is actually correct behavior; this article will be revised soon to address this change.
</p><p><b>Note 2</b>: 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 header <code>Content-Type: application/xml</code>, IE will throw a JavaScript error, 'Object Expected', after the line where you try to access an XML element. If you do not set header <code>Cache-Control: no-cache</code> the browser will cache the response and never re-submit the request, making debugging "challenging."
</p><p><b>Note 3</b>: if the <code>httpRequest</code> variable is used globally, competing functions calling <code>makeRequest()</code> may overwrite each other, causing a race condition.  Declaring the <code>httpRequest variable</code> local to the function and passing it to the <code>alertContent()</code> function prevents the race condition.
</p><p><b>Note 4</b>: To register the callback function <code>onreadystatechange</code>, you cannot have any arguments. That's why the following code does not work:
</p>
<pre>httpRequest.onreadystatechange = alertContents(httpRequest); // (does not work)
</pre>
<p>So, to register the function successfully, you can either pass the arguments indirectly via the anonymous function or use <code>httpRequest</code> as a global variable. Examples follow:
</p>
<pre>httpRequest.onreadystatechange = function() { alertContents(httpRequest); };  //1 (simultaneous request)
httpRequest.onreadystatechange = alertContents;  //2 (global variable)
</pre>
<p>Method 1 lets you have several requests processed simultaneously, while method 2 is used if <code>httpRequest</code> is a global variable.
</p><p><br>
<b>Note 5</b>: In the event of a communication error (such as the webserver going down), an exception will be thrown in the onreadystatechange method when attempting to access the .status variable. Make sure that you wrap your if...then statement in a try...catch. (See: {{template.Bug(238559)}}).
</p>
<pre>function alertContents(httpRequest) {

        try {
            if (httpRequest.readyState == 4) {
                if (httpRequest.status == 200) {
                    alert(httpRequest.responseText);
                } else {
                    alert('There was a problem with the request.');
                }
            }
        }
        catch( e ) {
            alert('Caught Exception: ' + e.description);
        }

    }
</pre>
<h3 name="Step_4_.E2.80.93_.22The_X-Files.22_or_Working_with_the_XML_Response"> Step 4 – "The X-Files" or Working with the XML Response </h3>
<p>In the previous example, after the response to the HTTP request was received we used the <code>responseText</code> property of the request object, which contained the contents of the <tt>test.html</tt> file. Now let's try the <code>responseXML</code> property.
</p><p>First off, let's create a valid XML document that we'll request later on. The document (<tt>test.xml</tt>) contains the following:
</p>
<pre>&lt;?xml version="1.0" ?&gt;
&lt;root&gt;
    I'm a test.
&lt;/root&gt;
</pre>
<p>In the script we only need to change the request line to:
</p>
<pre>...
onclick="makeRequest('test.xml')"&gt;
...
</pre>
<p>Then in <code>alertContents()</code>, we need to replace the line <code>alert(httpRequest.responseText);</code> with:
</p>
<pre>var xmldoc = httpRequest.responseXML;
var root_node = xmldoc.getElementsByTagName('root').item(0);
alert(root_node.firstChild.data);
</pre>
<p>This code takes the <code>XMLDocument</code> object given by <code>responseXML</code> and uses DOM methods to access some of the data contained in the XML document. You can see the <code>test.xml</code> <a class="external" href="http://www.w3clubs.com/mozdev/test.xml">here</a> and the updated test script <a class="external" href="http://www.w3clubs.com/mozdev/httprequest_test_xml.html">here</a>.
</p><p>For more on DOM methods, be sure to check <a class="external" href="http://www.mozilla.org/docs/dom/">Mozilla's DOM implementation</a> documents.
</p>{{ wiki.languages( { "ca": "ca/AJAX/Primers_passos", "de": "de/AJAX/Getting_Started", "es": "es/AJAX/Primeros_Pasos", "fr": "fr/AJAX/Premiers_pas", "it": "it/AJAX/Iniziare", "ja": "ja/AJAX/Getting_Started", "ko": "ko/AJAX/Getting_Started", "pl": "pl/AJAX/Na_pocz\u0105tek", "pt": "pt/AJAX/Como_come\u00e7ar", "zh-cn": "cn/AJAX/\u5f00\u59cb", "ru": "ru/AJAX/\u0421_\u0447\u0435\u0433\u043e_\u043d\u0430\u0447\u0430\u0442\u044c" } ) }}
Revert to this revision