SlideShare a Scribd company logo
1 of 7
Download to read offline
AJAX:Getting Started - MDC                                                      http://developer.mozilla.org/en/docs/AJAX:Getting_Started




                AJAX:Getting Started
                 From MDC

               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




                What's AJAX?                                                                                    [edit]

               AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful
               browser features that have been around for years, but were overlooked by many 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



                Step 1 – say "Please!" or How to Make an HTTP Request                                           [edit]

               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, 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:




1 of 7                                                                                                              2/21/2006 10:36 AM
AJAX:Getting Started - MDC                                                 http://developer.mozilla.org/en/docs/AJAX:Getting_Started




                   if (window.XMLHttpRequest) { // Mozilla, Safari, ...
                       http_request = new XMLHttpRequest();
                   } else if (window.ActiveXObject) { // IE
                       http_request = 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.


                   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 setting the
               onreadystatechange 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 call the open() and send() 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 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




2 of 7                                                                                                         2/21/2006 10:36 AM
AJAX:Getting Started - MDC                                                http://developer.mozilla.org/en/docs/AJAX:Getting_Started




                      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 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:


                   http_request.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                                  [edit]

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

               http_request.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 (http_request.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)




3 of 7                                                                                                        2/21/2006 10:36 AM
AJAX:Getting Started - MDC                                               http://developer.mozilla.org/en/docs/AJAX:Getting_Started




                      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 (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 as an XMLDocument object
                      you can traverse using the JavaScript DOM functions



                Step 3 – "All together now!" - A Simple Example                                          [edit]

               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.




4 of 7                                                                                                       2/21/2006 10:36 AM
AJAX:Getting Started - MDC                                              http://developer.mozilla.org/en/docs/AJAX:Getting_Started




                   <script type="text/javascript" language="javascript">

                       var http_request = false;

                       function makeRequest(url) {

                             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 = alertContents;
                             http_request.open('GET', url, true);
                             http_request.send(null);

                       }

                       function alertContents() {

                             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 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




5 of 7                                                                                                      2/21/2006 10:36 AM
AJAX:Getting Started - MDC                                                 http://developer.mozilla.org/en/docs/AJAX:Getting_Started




                      alertContents() ;
                      alertContents() checks if the response was received and it's an OK and then
                      alert()s the contents of the test.html file.

               You can test the example here     and you can see the test file here .

               Note: The line http_request.overrideMimeType('text/xml'); above will cause
               Javascript Console errors in Firefox 1.5b as documented 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 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'.



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

               In the previous example, after the response to the HTTP request was received, we used
               the reponseText property of the request object and it contained the contents of the
               test.html 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
               (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 with:


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


               Then in alertContents() we need to replace the alert()-ing line
               alert(http_request.responseText); with:




6 of 7                                                                                                         2/21/2006 10:36 AM
AJAX:Getting Started - MDC                                            http://developer.mozilla.org/en/docs/AJAX:Getting_Started




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


               This way we took the XMLDocument object given by responseXML and we used DOM
               methods to access some data contained in the XML document. You can see the test.xml
               here    and the updated test script here .

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

                 Retrieved from "http://developer.mozilla.org/en/docs/AJAX:Getting_Started "




7 of 7                                                                                                    2/21/2006 10:36 AM

More Related Content

What's hot

AJAX
AJAXAJAX
AJAXARJUN
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection apiMatthieu Aubry
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servletvikram singh
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAnuchit Chalothorn
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryWeb services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryFulvio Corno
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkStefano Paluello
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHPZoran Jeremic
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGHitesh Mohapatra
 
Ado.net session13
Ado.net session13Ado.net session13
Ado.net session13Niit Care
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_queryFajar Baskoro
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-frameworkSakthi Bro
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server PageVipin Yadav
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1Hitesh-Java
 

What's hot (20)

AJAX
AJAXAJAX
AJAX
 
25250716 seminar-on-ajax text
25250716 seminar-on-ajax text25250716 seminar-on-ajax text
25250716 seminar-on-ajax text
 
Easy rest service using PHP reflection api
Easy rest service using PHP reflection apiEasy rest service using PHP reflection api
Easy rest service using PHP reflection api
 
Request dispatching in servlet
Request dispatching in servletRequest dispatching in servlet
Request dispatching in servlet
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
AJAX
AJAXAJAX
AJAX
 
Android App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web ServicesAndroid App Development 06 : Network &amp; Web Services
Android App Development 06 : Network &amp; Web Services
 
Web based development
Web based developmentWeb based development
Web based development
 
Web services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP libraryWeb services in PHP using the NuSOAP library
Web services in PHP using the NuSOAP library
 
Using MongoDB with the .Net Framework
Using MongoDB with the .Net FrameworkUsing MongoDB with the .Net Framework
Using MongoDB with the .Net Framework
 
Consuming RESTful services in PHP
Consuming RESTful services in PHPConsuming RESTful services in PHP
Consuming RESTful services in PHP
 
JDBC
JDBCJDBC
JDBC
 
22jdbc
22jdbc22jdbc
22jdbc
 
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDINGWORKING WITH FILE AND PIPELINE PARAMETER BINDING
WORKING WITH FILE AND PIPELINE PARAMETER BINDING
 
Ado.net session13
Ado.net session13Ado.net session13
Ado.net session13
 
1 ppt-ajax with-j_query
1 ppt-ajax with-j_query1 ppt-ajax with-j_query
1 ppt-ajax with-j_query
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
JSP - Java Server Page
JSP - Java Server PageJSP - Java Server Page
JSP - Java Server Page
 
Ado.Net
Ado.NetAdo.Net
Ado.Net
 
Hibernate - Part 1
Hibernate - Part 1Hibernate - Part 1
Hibernate - Part 1
 

Viewers also liked

Learning through the_arts
Learning through the_artsLearning through the_arts
Learning through the_artsSaFaRiNa84
 
Dentin -kunal parekh..advancd oral biology
Dentin -kunal parekh..advancd oral biologyDentin -kunal parekh..advancd oral biology
Dentin -kunal parekh..advancd oral biologyKunal Parekh
 
Social can learn from tradicional customer service
Social can learn from tradicional customer serviceSocial can learn from tradicional customer service
Social can learn from tradicional customer serviceCentrecom
 
A Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western WallA Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western WallLeib Tropper
 
Androidprojecttitle2015 2016-151007054022-lva1-app6891
Androidprojecttitle2015 2016-151007054022-lva1-app6891Androidprojecttitle2015 2016-151007054022-lva1-app6891
Androidprojecttitle2015 2016-151007054022-lva1-app6891Salem Spiro
 
Presentation for kpt6044 t1
Presentation for kpt6044 t1Presentation for kpt6044 t1
Presentation for kpt6044 t1kannadhass
 
Four Ways to Leverage Social Media in Your Marketing
Four Ways to Leverage Social Media in Your MarketingFour Ways to Leverage Social Media in Your Marketing
Four Ways to Leverage Social Media in Your MarketingJocelyn Murray
 
global child care powerpoint
global child care powerpointglobal child care powerpoint
global child care powerpointWendySteph
 
Foundation Portfolio Evaluation
Foundation Portfolio EvaluationFoundation Portfolio Evaluation
Foundation Portfolio EvaluationAmyLongworth
 
திறம்பட கற்றல்
திறம்பட கற்றல்திறம்பட கற்றல்
திறம்பட கற்றல்Kaviarasi Selvaraju
 
Mbdou detsad 59
Mbdou detsad 59Mbdou detsad 59
Mbdou detsad 59klepa.ru
 

Viewers also liked (15)

Learning through the_arts
Learning through the_artsLearning through the_arts
Learning through the_arts
 
Dentin -kunal parekh..advancd oral biology
Dentin -kunal parekh..advancd oral biologyDentin -kunal parekh..advancd oral biology
Dentin -kunal parekh..advancd oral biology
 
Data entry
Data entryData entry
Data entry
 
Social can learn from tradicional customer service
Social can learn from tradicional customer serviceSocial can learn from tradicional customer service
Social can learn from tradicional customer service
 
A Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western WallA Historical Glimpse at Jerusalem’s Western Wall
A Historical Glimpse at Jerusalem’s Western Wall
 
Androidprojecttitle2015 2016-151007054022-lva1-app6891
Androidprojecttitle2015 2016-151007054022-lva1-app6891Androidprojecttitle2015 2016-151007054022-lva1-app6891
Androidprojecttitle2015 2016-151007054022-lva1-app6891
 
Fragance
FraganceFragance
Fragance
 
Samsung+Guru200+specification
Samsung+Guru200+specificationSamsung+Guru200+specification
Samsung+Guru200+specification
 
Presentation for kpt6044 t1
Presentation for kpt6044 t1Presentation for kpt6044 t1
Presentation for kpt6044 t1
 
Four Ways to Leverage Social Media in Your Marketing
Four Ways to Leverage Social Media in Your MarketingFour Ways to Leverage Social Media in Your Marketing
Four Ways to Leverage Social Media in Your Marketing
 
global child care powerpoint
global child care powerpointglobal child care powerpoint
global child care powerpoint
 
Foundation Portfolio Evaluation
Foundation Portfolio EvaluationFoundation Portfolio Evaluation
Foundation Portfolio Evaluation
 
திறம்பட கற்றல்
திறம்பட கற்றல்திறம்பட கற்றல்
திறம்பட கற்றல்
 
Mbdou detsad 59
Mbdou detsad 59Mbdou detsad 59
Mbdou detsad 59
 
Informatica
InformaticaInformatica
Informatica
 

Similar to Ajax (20)

Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
M Ramya
M RamyaM Ramya
M Ramya
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 
Ajax Fundamentals Web Applications
Ajax Fundamentals Web ApplicationsAjax Fundamentals Web Applications
Ajax Fundamentals Web Applications
 
AJAX
AJAXAJAX
AJAX
 
Using Ajax In Domino Web Applications
Using Ajax In Domino Web ApplicationsUsing Ajax In Domino Web Applications
Using Ajax In Domino Web Applications
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax Introduction
 
Ajax Technology
Ajax TechnologyAjax Technology
Ajax Technology
 
Ajax
AjaxAjax
Ajax
 

More from vantinhkhuc (20)

Url programming
Url programmingUrl programming
Url programming
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Security overview
Security overviewSecurity overview
Security overview
 
Rmi
RmiRmi
Rmi
 
Md5
Md5Md5
Md5
 
Lecture17
Lecture17Lecture17
Lecture17
 
Lecture11 b
Lecture11 bLecture11 b
Lecture11 b
 
Lecture10
Lecture10Lecture10
Lecture10
 
Lecture9
Lecture9Lecture9
Lecture9
 
Lecture6
Lecture6Lecture6
Lecture6
 
Jsse
JsseJsse
Jsse
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Jsp examples
Jsp examplesJsp examples
Jsp examples
 
Jpa
JpaJpa
Jpa
 
Ejb examples
Ejb examplesEjb examples
Ejb examples
 
Corba
CorbaCorba
Corba
 
Ejb intro
Ejb introEjb intro
Ejb intro
 
Chc6b0c6a1ng 12
Chc6b0c6a1ng 12Chc6b0c6a1ng 12
Chc6b0c6a1ng 12
 
Ch06
Ch06Ch06
Ch06
 

Ajax

  • 1. AJAX:Getting Started - MDC http://developer.mozilla.org/en/docs/AJAX:Getting_Started AJAX:Getting Started From MDC 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 What's AJAX? [edit] AJAX (Asynchronous JavaScript and XML) is a newly coined term for two powerful browser features that have been around for years, but were overlooked by many 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 Step 1 – say "Please!" or How to Make an HTTP Request [edit] 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, 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: 1 of 7 2/21/2006 10:36 AM
  • 2. AJAX:Getting Started - MDC http://developer.mozilla.org/en/docs/AJAX:Getting_Started if (window.XMLHttpRequest) { // Mozilla, Safari, ... http_request = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE http_request = 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. 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 setting the onreadystatechange 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 call the open() and send() 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 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 2 of 7 2/21/2006 10:36 AM
  • 3. AJAX:Getting Started - MDC http://developer.mozilla.org/en/docs/AJAX:Getting_Started 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 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: http_request.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 [edit] Remember that when you were sending the request, you provided the name of a JavaScript function that is designed to handle the response. http_request.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 (http_request.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) 3 of 7 2/21/2006 10:36 AM
  • 4. AJAX:Getting Started - MDC http://developer.mozilla.org/en/docs/AJAX:Getting_Started 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 (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 as an XMLDocument object you can traverse using the JavaScript DOM functions Step 3 – "All together now!" - A Simple Example [edit] 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. 4 of 7 2/21/2006 10:36 AM
  • 5. AJAX:Getting Started - MDC http://developer.mozilla.org/en/docs/AJAX:Getting_Started <script type="text/javascript" language="javascript"> var http_request = false; function makeRequest(url) { 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 = alertContents; http_request.open('GET', url, true); http_request.send(null); } function alertContents() { 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 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 5 of 7 2/21/2006 10:36 AM
  • 6. AJAX:Getting Started - MDC http://developer.mozilla.org/en/docs/AJAX:Getting_Started alertContents() ; alertContents() checks if the response was received and it's an OK and then alert()s the contents of the test.html file. You can test the example here and you can see the test file here . Note: The line http_request.overrideMimeType('text/xml'); above will cause Javascript Console errors in Firefox 1.5b as documented 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 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'. Step 4 – "The X-Files" or Working with the XML Response [edit] In the previous example, after the response to the HTTP request was received, we used the reponseText property of the request object and it contained the contents of the test.html 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 (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 with: ... onclick="makeRequest('test.xml')"> ... Then in alertContents() we need to replace the alert()-ing line alert(http_request.responseText); with: 6 of 7 2/21/2006 10:36 AM
  • 7. AJAX:Getting Started - MDC http://developer.mozilla.org/en/docs/AJAX:Getting_Started var xmldoc = http_request.responseXML; var root_node = xmldoc.getElementsByTagName('root').item(0); alert(root_node.firstChild.data); This way we took the XMLDocument object given by responseXML and we used DOM methods to access some data contained in the XML document. You can see the test.xml here and the updated test script here . For more on the DOM methods, be sure to check Mozilla's DOM implementation documents. Retrieved from "http://developer.mozilla.org/en/docs/AJAX:Getting_Started " 7 of 7 2/21/2006 10:36 AM