SlideShare una empresa de Scribd logo
1 de 10
Descargar para leer sin conexión
Chap 3. Programming in Ajax      1



                        3. Programming in Ajax - Part I
 1.   Write program that asks the user to click a button, fetches data from a text file using Ajax
      techniques, and displays that data in the same web page without refreshing the whole page.
      The HTML file (AJAX1.HTML) is shown below:

      <html>
      <head>
      <title>Ajax at Work</title>
      <script language = "javascript">
           var xhobj = false;

              if(window.XMLHttpRequest)
              {
                   xhobj = new XMLHttpRequest();
              }
              else if (window.ActiveXObject)
              {
                   xhobj = new ActiveXObject("Microsoft.XMLHTTP");
              }

              function getData(dataSource, divID)
              {
                   if(xhobj)
                   {
                         var obj = document.getElementById(divID);
                         xhobj.open("GET", dataSource);

                               xhobj.onreadystatechange = function()
                               {
                                    if(xhobj.readyState == 4 && xhobj.status == 200)
                                    {
                                          obj.innerHTML = xhobj.responseText;
                                    }
                               }
                               xhobj.send(null);
                }
           }
      </script>
      </head>
      <body>
           <h1>Fetching data with Ajax</h1>

              <form>
              <input type = "button" value = "Display Message " onclick =
              "getData('http://localhost/AJAX/data.txt', 'targetDiv')">

              </form>
              <div id = "targetDiv">
                        <p>The data fetched will go here</p>
              </div>
      </body>
      </html>
      The text file is data.txt and it has just one line in it: Hooray!! Hooray!! This is displayed by Ajax


mukeshtekwani@hotmail.com                                                          Prof. Mukesh N. Tekwani
2    Programming in Ajax


         Analysis of the above program:
           1.    Consider the body of the HTML document. We display a button on this page by creating a <form>
                 element.
           2.    We have also created a <div> element called “tartgetDiv” in which the fetched data will be displayed.
           3.    When the user clicks on this button, a JavaScript function called getData() is called. We use the onclick()
                 event for this purpose.
           4.    The getData() function is passed 2 strings :
                      a. The name of the text file DATA.TXT to fetch from the server, and
                      a. The name of the <div> element to display the fetched text in.
           5.    In the <head> section of the HTML document we create the JavaScript code starting with the line :
                 <script language = "javascript">
           6.    Within the script, we create a variable to store the data, and an XMLHttpRequest object is created to set
                 up a connection with the server and retrieve the data from the text file.
           7.    The code to create the XMLHttpRequest object is outside any function, so this code runs immediately as
                 the page loads.
           8.    We create a variable for this object var xhobj = false; This variable is initialized to the value ‘false’ so
                 that the script can check later whether the variable was created.
           9.    The XMLHttpRequest object is part of the browser’s window object. So to check whether the
                 XMLHttpRequest object is ready to use, we use the if statement. If XMLHttpRequest object is available,
                 we can create the object as follows, for non_IE browsers:
                           if(window.XMLHttpRequest)
                           {
                                     xhobj = new XMLHttpRequest();
                           }
                 If we are working with Internet Explorer, we can create an XMLHttpRequest object like this:
                           else if (window.ActiveXObject)
                           {
                                     xhobj = new ActiveXObject("Microsoft.XMLHTTP");                                  }
                 Now we have the XMLHttpRequest object.
          10.    The onreadystatechange property holds the name of the event handler that should be called when
                 the value of the readyState property changes.
          11.    The readyState property holds the state of the request.
          12.    The getData() function will be used to actually fetch the text data from the file.
          13.    We first check that there is a valid object with the statement if (xhobj)
          14.    If the object creation hadn’t worked, then this variable will hold a value ‘false’ and the condition would
                 become false.
          15.    Now we have the xhobj variable. This object has a method called “open()”. We will use that method to
                 use the URL we want. Syntax of open() method is:
                 open (“method”, “URL”, [,asyncFlag [, “username” [,                                “password”]]])
             • method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD
             • URL – the requested URL
             • asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is
                 ‘true’ (asynchronous)
          16.    The URL we want to fetch is passed to the getData() function as the dataSource argument
          17.    To open a URL we can use the GET, POST or PUT methods. But in this example we use the GET
                 method.
          18.    Now, xhobj is ready to use the URL we have given. But it does not connect to that file.
          19.    By default the connection to this file is made asynchronously. It means that this statement does not wait
                 until the connection is made and the data is finished downloading
          20.    The XMLHttpRequest object has a property called onreadystatechange that lets us handle
                 asynchronous loading operations.
          21.    If we assign the name of a JavaScript function to this property, that function will be called each time the
                 XMLHttpRequest object’s status changes.
                           xhobj.onreadystatechange = function()
          22.    We have used a shortcut to assign a JavaScript function to the onreadystatechange property. We
                 have created an anonymous function because the function does not have any name. Such a function is
                 created on the fly, just by using the keyword function(). Then we define the body of this function in
                 curly braces. This new anonymous function will be called whenever the XMLHttpRequest object
                 undergoes a change.


    Prof. Mukesh N Tekwani                                                           mukeshtekwani@hotmail.com
Chap 1. Introduction to Ajax           3


       23.   The XMLHttpRequest object has 2 properties that are important for us. The readyState property
             that tells us how the data downloading is progressing. The readyState property can have these
             values:
                               0 – uninitialized
                               1 – loading
                               2 – loaded
                               3 – interactive
                               4 – complete
             We have used the value 4, which means the data is downloaded.
       24.   The status property tells us the status of the download itself. It is the standard HTTP status code that
             the browser got for the URL we supplied. The possible values of status are:
                           • 200 – all OK
                           • 400 – Bad request
                           • 403 – Forbidden
                           • 404 – Not found
                           • 408 – request time out
                           • 414 – Requested URL too long

             So here is the meaning of the statement
             if(xhobj.readyState == 4 && xhobj.status == 200)

             It means we are checking that the data has been downloaded completely (readyState = 4) and
             everything went ok with the request to the server (status = 200)
       25.   The data has been fetched from the server. Now to get the data on the Web page we use one of these
             techniques:
                 – If we want to treat the data as standard text, we use the object’s responseText property.
                 – If the data is in XML format, we can use the responseXML property.
       26.   To make the test appear on the page, we assign that text to the <div> element whose ID is targetDiv.
             This ID was passed to the getData() function.
       27.   To connect to the server to get the response we use the send() method. When we are using the GET
             method, we send a value of null to connect to the server and request the data using the XMLHttpRequest
             object.
                      xhobj.send(null);
      28.    The send() method actually downloads the data so that the anonymous function can handle that data.

 2.   Write a note on the XMLHttpRequest object. What are its properties and methods?
        1.   The XMLHttpRequest object is created to set up a connection with the server and retrieve the data from
             the text file from the web server without reloading the entire page.
        2.   This objet supports any text and XML formats.
        3.   It can be used to make requests over both HTTP and HTTPS protocols.
        4.   The XMLHttpRequest object is part of the browser’s window object.
        5.   We can create the XMLHttpRequest object as follows for non-IE browsers:
             if(window.XMLHttpRequest)
             {
                       xhobj = new XMLHttpRequest();
             }
             For IE browser, we create the XMLHttpRequest object as follows:
             if (window.ActiveXObject)
             {
                       xhobj = new ActiveXObject("Microsoft.XMLHTTP");
             }
             The first method shown above also works for IE 8 (yes, it has been tested by me!)
                              Events of XMLHttpRequest object for Internet Explorer
             Property                                          Description
       onreadystatechange     Holds the name of the event holder that should be called when the value of the
                              readyState property changes.
       ontimeout              This event is raised when there is an error that prevents the completion of the
                              request.


mukeshtekwani@hotmail.com                                                            Prof. Mukesh N. Tekwani
4    Programming in Ajax


                                    Properties of XMLHttpRequest object for Internet Explorer

                   Property                                             Description
            readyState                Holds the state of the request
            responseBody              Holds a response body which is one way HTTP responses can be returned.
            responseStream            Holds a response stream ( a binary stream)
            responseText              Holds the response body as a string
            responseXML               Holds the response body as XML
            Status                    Holds the HTTP status code returned by a request
            statusText                Holds the HTTP response status text
            Timeout                   Gets or sets the timeout value.

                                     Methods of XMLHttpRequest object for Internet Explorer

                    Method                                                 Description
            Abort                         Aborts the HTTP request
            getAllResponseHeaders         Gets all the HTTP headers
            getResponseHeader             Gets the value of an HTTP header
            Open                          Opens a request to a server
            Send                          Sends an HTTP request to the server
            setRequestHeader              Sets the name and value of an HTTP header

          The open() method:
          Syntax:
          open (“method”, “URL”, [,asyncFlag [, “username” [,                                 “password”]]])

              •    method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD
              •    URL – the requested URL
              •    asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is
                   ‘true’ (asynchronous)

          The send() method:
          Syntax:
          object.send( [var])
          This method is synchronous or asynchronous, depending on the value of the asyncFlag in the open method call. If
          asynchronous, this call returns immediately.

          The onreadystatechange event:
          This holds the name of the event holder that should be called when the value of the readyState property changes.

          The following script shows how to set an asynchronous event handler that alerts the user when the readyState
          property of the request reaches ‘complete’(value 4).

          xhobj.onreadystatechange = function()
          {
                if(xhobj.readyState == 4 && xhobj.status == 200)
                {
                      alert('Transfer complete.');
                }
          }

          The responseText property:
          It retrieves the response body as a string. It is a rad-only property and has no default value.

          Syntax
          sBody = object.responseText


     3.   What are the steps in creating an Ajax program?
          The various steps in creating an Ajax program are as follows:

    Prof. Mukesh N Tekwani                                                              mukeshtekwani@hotmail.com
Chap 1. Introduction to Ajax             5


      1.   Create an instance of the XMLHTTPRequest object that will work across different browser implementations.
           This object is part of the browser’s window. We create the object as follows:
               var xhobj = false;

               if(window.XMLHttpRequest)
               {
                         xhobj = new XMLHttpRequest();
               }
      2.   Prepare a request using the onreadystatechange event handler, the open method, and the send
           method.
               xhobj.onreadystatechange = function()
      3.   Process the response from the server through the properties readyState, status, responseText, and
           sometimes responseXML.
               if(xhobj.readyState == 4 && xhobj.status == 200)
               {
                         obj.innerHTML = xhobj.responseText;
               }

 4.   How are asynchronous requests handled in Ajax?
      1.   The XMLHttpRequest object is the core of the Ajax engine.
      2.   It is the object that enables a page to get data from (using the GET method) or post data to (using the POST
           method) the server as a background request.
      3.   The browser is not refreshed during this process.
      4.   The XMLHttpRequest object eliminates the need to wait for the server to respond with a new page for each
           request. The user can continue to interact with the page while the requests are made in the background.
      5.   The most common formats in which we can receive data from XMLHttpRequest object is text or XML
           formats.
      6.   This object has a method called “open()”. We use that method to open the URL we want. Syntax of open()
           method is:
                 open (“method”, “URL”, [,asyncFlag [, “username” [,                             “password”]]])
                     • method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD
                     • URL – the requested URL
                     • asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous.
                          Default is ‘true’ (asynchronous)

 5.   Write a note on the XMLHttpRequest readyState property.
      The readyState property holds the status of the request sent by the client. This property has 4 possible values
      as follows:
      0 – uninitialized: The object has been created but not initialized (i.e. the open () method has not been called)
      1 – loading: Server connection has been established. A request has been opened but the send method has not
      been called.
      2 – loaded: A request s received. The send method has been called. No data is available yet.
      3 – interactive or processing request: A request has been opened. Some data is received but not all.
      4 – complete or request finished and response is ready.

      This is a read-only property and it does not have a default value. When the value of this property becomes we can
      obtain the responseText property to obtain the text returned by the server. It is used along with the status property.

 6.   Write a note on the status property of the XMLHttpRequest object.
      The status property tells us the status of the download. It is the standard HTTP status code that the browser got
      for the URL we supplied. The possible values of status are:
           • 200 – all OK
           • 400 – Bad request
           • 403 – Forbidden
           • 404 – Not found
           • 408 – request time out
           • 414 – Requested URL too long
      To make sure that the data has been downloaded completely and everything went OK, we must check that the
      readyState property has the value 4 and the status property has the value 200. This is doe as follows:

mukeshtekwani@hotmail.com                                                                  Prof. Mukesh N. Tekwani
6    Programming in Ajax


                   if(xhobj.readyState == 4 && xhobj.status == 200)
                   {
                         obj.innerHTML = xhobj.responseText;
                   }

     7.   Explain the innerHTML property.
          1.   Each HTML element has an innerHTML property that defines both the code and the text that appears
               between the element’s opening and closing tags.
          2.   Before we can change the text that appears within the element tags, we must give an id (like a name) to this
               element.
          3.   Once the id has been given, we can use the getElementById function
          4.   The innerHTML property sets or returns the inner HTML of an element.
          5.   The innerHTML property can contain text and HTML elements.
          6.   When this property is set, the given string completely replaces the existing content of the object.
          7.   If the string contains HTML tags, the string is parsed and formatted.

          Example:

          <html>
          <head>
          <script type="text/javascript">
          function changeText()
          {
                 document.getElementById('boldStuff').innerHTML =
                       "<font color='blue'>My Dearest Friends</font>";
          }
          </script>
          </head>
          <body>
          <p>Welcome to the site <b id='boldStuff'>dude</b></p>
          <input type='button' onclick='changeText()' value='Change Text'/>
          </body>
          </html>

     8.   Write Ajax code to display three images on a web page. When the user moves the mouse over any
          image, the application fetches the text for that mouseover event using Ajax.
          We first create the HTML page AJAX2.HTML:

          <html>
          <head>
          <title>Ajax at Work</title>
          <script language = "javascript">
          var xhr = false;

          if(window.XMLHttpRequest)
          {
                xhr = new XMLHttpRequest();
          }
          else if (window.ActiveXObject)
          {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
          }

          function getData(dataSource, divID)
          {
                if(xhr)
                {
                      var obj = document.getElementById(divID);
                      xhr.open("GET", dataSource);
                      xhr.onreadystatechange = function()

    Prof. Mukesh N Tekwani                                                          mukeshtekwani@hotmail.com
Chap 1. Introduction to Ajax            7


                        {
                                 if(xhr.readyState == 4 && xhr.status == 200)
                                 {
                                       obj.innerHTML = xhr.responseText;
                                 }
                        }
                        xhr.send(null);
             }
      }
      </script>
      </head>
      <body>
      <h1>Interactive Mouseovers</h1>

      <img src = "yahoo.jpg"
      onmouseover="getData('http://localhost/AJAX/yahoo.txt','targetDiv')">

      <img src = "rediff.jpg"
      onmouseover="getData('http://localhost/AJAX/rediff.txt','targetDiv')">

      <img src = "altavista.jpg"
      onmouseover="getData('http://localhost/AJAX/altavista.txt','targetDiv')">

      <div id = "targetDiv">
             <p>Search the web with these search engines</p>
      </div>
      </body>
      </html>

      The HTML file displays 3 images of three popular search engines in the <body> element. We connect the
      getData() function with the onmouseover() event. The getData function will fetch the text from the respective file.

      Next we create the 3 text files. The contents of each text file are shown:
      File:Altavista.txt, Content: <font color = 'red'>Altavista - was the king once upon a time</font>
      File:Rediff.txt, Content: Rediffmail portal - Recently main features have been updated.
      File:Yahoo.txt, Content: Yahoo portal - Mail, News, Chat, and more




 9.   What is server-side scripting? Which are the server-side scripting languages?
      1. Server-side scripts are programs that can run on the server.
      2. Normally when a browser requests an HTML file, the server returns the file, but if the file contains a server-
         side script, the script inside the HTML file is executed by the server before the file is returned to the browser
         as plain HTML.
      3. Server-side scripts can do the following:
                   a. Dynamically change the content of a web page
                   b. Return data from a database

mukeshtekwani@hotmail.com                                                                Prof. Mukesh N. Tekwani
8    Programming in Ajax


                     c. Customize the web page so as to make it more useful; for the user.
                     d. Provide security since the server-side code cannot be viewed from the browser.
          4. The two common scripting languages are ASP and PHP.

    10.   Write the Ajax code that uses a PHP script on a server to display a message when the user clicks
          on a command button.
          The PHP file is DATA.PHP shown below:
          <?php
                 echo ‘This text was fetched using Ajax.’;
          ?>

          The HTML file AJAX3.HTML is as follows:

          <html>
          <head>
          <title>Ajax and PHP at work</title>
          <script language = "javascript">
          var xhr = false;

          if (window.XMLHttpRequest)
          {
                xhr = new XMLHttpRequest();
          }
          else if (window.ActiveXObject)
          {
                xhr = new ActiveXObject("Microsoft.XMLHTTP");
          }

          function getData(dataSource, divID)
          {
                if(xhr)
                {
                      var obj = document.getElementById(divID);
                      xhr.open("GET", dataSource);
                      xhr.onreadystatechange = function()
                      {
                            if (xhr.readyState == 4 && xhr.status == 200)
                            {
                                  obj.innerHTML = xhr.responseText;
                            }
                      }
                      xhr.send(null);
                }
          }
          </script>
          </head>

          <body>
          <H1>Fetching data with Ajax and PHP</H1>
          <form>
                 <input type = "button" value = "Display Message"
                 onclick = "getData('data.php', 'targetDiv')">
          </form>

          <div id="targetDiv">
                 <p>The fetched data will go here.</p>
          </div>

          </body>
          </html>


    Prof. Mukesh N Tekwani                                                       mukeshtekwani@hotmail.com
Chap 1. Introduction to Ajax   9


11.   Write the code to show how to retrieve data from an XML document.
      Consider the following XML code in the AJAX5NOTE.XML:

      <note>
            <to>Raja </to>
            <from>Jani</from>
            <heading>Reminder</heading>
            <body>Don't forget me this weekend!</body>
      </note>

      The Ajax code to retrieve this XML file is as follows (AJAX5.HTML):

      <html>
      <head>
      <script type="text/javascript">
      function loadXMLDoc(url)
      {
             if (window.XMLHttpRequest)
             {
                   xhr = new XMLHttpRequest();
             }
             else
             {
                   xhr = new ActiveXObject("Microsoft.XMLHTTP");
             }
             xhr.onreadystatechange=function()
             {
                   if (xhr.readyState == 4 && xhr.status == 200)
                   {
                     document.getElementById('A1').innerHTML = xhr.status;
                     document.getElementById('A2').innerHTML = xhr.statusText;
                     document.getElementById('A3').innerHTML = xhr.responseText;
                   }
             }
             xhr.open("GET", url, true);
             xhr.send(null);
      }
      </script>
      </head>

      <body>
            <h2>Retrieving data from XML file</h2>
            <p><b>Status:           </b><span id="A1"></span></p>
            <p><b>Status text:      </b><span id="A2"></span></p>
            <p><b>Response:         </b><span id="A3"></span></p>
            <button onclick = "loadXMLDoc('/note.xml')">
                  Get XML data</button>
      </body>
      </html>




mukeshtekwani@hotmail.com                                                      Prof. Mukesh N. Tekwani
10    Programming in Ajax




     12.   Explain the techniques by which Ajax passes data to the server.
           1. Ajax can pass data to the server either by the GET or by the POST method.
           2. If we use the GET method, the data sent is public as it can be seen in the browser’s address bar. This method
              uses URL encoding. It means that the data that is being sent is appended to the actual URL.
           3. Suppose we have a text field named ‘a’ that contains the number 5, another text filed called ‘b’ that contains
              the text “centuries”, then all this data will be encoded and added to the URL. A question mark is ended to
              the end of the URL and data is added in the form name=value. Spaces are converted into a + sign and we
              separate the pairs of name=data by the ‘&’ sign.
           4. So the complete URL becomes: www.servername.com/scriptname?a=5&b=centuries
           5. All data sent this way is text, even if we send numbers.
           6. The JavaScript escape function will encode data for appending to the end of the URL. This function will
              also convert spaces into the + symbol.
           7. When we pass data to a URL by using the POST method, it is encoded internally and data is more
              secure.

                                          PROGRAMMING EXERCISES
           Modify the program in Q 1 so that it displays an alert box when the transfer of data is complete.
           Modify the following if statement as shown below:

           if(xhobj.readyState == 4 && xhobj.status == 200)
           {
                 alert('Transfer complete.');
           }

           Modify the program in Q 1 so that the page displays 2 command buttons. When the user clicks
           on the first button, the program fetches data from a file data1.txt. When the user clicks on the
           second command button, the program should fetch data from the file data2.txt and display that
           data in the same web page without refreshing the whole page.




     Prof. Mukesh N Tekwani                                                          mukeshtekwani@hotmail.com

Más contenido relacionado

La actualidad más candente

Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server controlSireesh K
 
Di web tech mail (no subject)
Di web tech mail   (no subject)Di web tech mail   (no subject)
Di web tech mail (no subject)shubhamvcs
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applicationsAlex Golesh
 
Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5johnwilander
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppMichele Capra
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stackTomáš Kypta
 
Data Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementData Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementMongoDB
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennJavaDayUA
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMJonathan Wage
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WPNguyen Tuan
 

La actualidad más candente (17)

Url programming
Url programmingUrl programming
Url programming
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Ajax Lecture Notes
Ajax Lecture NotesAjax Lecture Notes
Ajax Lecture Notes
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server control
 
Di web tech mail (no subject)
Di web tech mail   (no subject)Di web tech mail   (no subject)
Di web tech mail (no subject)
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applications
 
Introduction to JSON & AJAX
Introduction to JSON & AJAXIntroduction to JSON & AJAX
Introduction to JSON & AJAX
 
Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5Web Integration Patterns in the Era of HTML5
Web Integration Patterns in the Era of HTML5
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Test and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 AppTest and profile your Windows Phone 8 App
Test and profile your Windows Phone 8 App
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
 
Modern Android app library stack
Modern Android app library stackModern Android app library stack
Modern Android app library stack
 
Data Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data ManagementData Management 3: Bulletproof Data Management
Data Management 3: Bulletproof Data Management
 
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp KrennPaintfree Object-Document Mapping for MongoDB by Philipp Krenn
Paintfree Object-Document Mapping for MongoDB by Philipp Krenn
 
ZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODMZendCon2010 Doctrine MongoDB ODM
ZendCon2010 Doctrine MongoDB ODM
 
09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP09.Local Database Files and Storage on WP
09.Local Database Files and Storage on WP
 

Destacado (15)

Ajax chap 3
Ajax chap 3Ajax chap 3
Ajax chap 3
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
AJAX
AJAXAJAX
AJAX
 
Ajax 101 Workshop
Ajax 101 WorkshopAjax 101 Workshop
Ajax 101 Workshop
 
TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI TYCS Ajax practicals sem VI
TYCS Ajax practicals sem VI
 
Dom
DomDom
Dom
 
Ajax Part II
Ajax Part IIAjax Part II
Ajax Part II
 
Ajax part i
Ajax part iAjax part i
Ajax part i
 
Perl Chapter 1
Perl Chapter 1Perl Chapter 1
Perl Chapter 1
 
S.E. DBMS-Paper Analysis
S.E. DBMS-Paper AnalysisS.E. DBMS-Paper Analysis
S.E. DBMS-Paper Analysis
 
Python reading and writing files
Python reading and writing filesPython reading and writing files
Python reading and writing files
 
XML
XMLXML
XML
 
OSI Model - Every Detail Explained
OSI Model - Every Detail ExplainedOSI Model - Every Detail Explained
OSI Model - Every Detail Explained
 
TCP-IP Reference Model
TCP-IP Reference ModelTCP-IP Reference Model
TCP-IP Reference Model
 
OSI Model of Networking
OSI Model of NetworkingOSI Model of Networking
OSI Model of Networking
 

Similar a Ajax chap 2.-part 1 (20)

Ajax
AjaxAjax
Ajax
 
Ajax Tuturial
Ajax TuturialAjax Tuturial
Ajax Tuturial
 
Ajax
AjaxAjax
Ajax
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
Ajax for dummies, and not only.
Ajax for dummies, and not only.Ajax for dummies, and not only.
Ajax for dummies, and not only.
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Ajax
AjaxAjax
Ajax
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax Technology
Ajax TechnologyAjax Technology
Ajax Technology
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8
 

Más de Mukesh Tekwani

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelMukesh Tekwani
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfMukesh Tekwani
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - PhysicsMukesh Tekwani
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion Mukesh Tekwani
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Mukesh Tekwani
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversionMukesh Tekwani
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion Mukesh Tekwani
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversionMukesh Tekwani
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Mukesh Tekwani
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prismMukesh Tekwani
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surfaceMukesh Tekwani
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomMukesh Tekwani
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesMukesh Tekwani
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEMukesh Tekwani
 

Más de Mukesh Tekwani (20)

Computer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube ChannelComputer Science Made Easy - Youtube Channel
Computer Science Made Easy - Youtube Channel
 
The Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdfThe Elphinstonian 1988-College Building Centenary Number (2).pdf
The Elphinstonian 1988-College Building Centenary Number (2).pdf
 
Circular motion
Circular motionCircular motion
Circular motion
 
Gravitation
GravitationGravitation
Gravitation
 
ISCE-Class 12-Question Bank - Electrostatics - Physics
ISCE-Class 12-Question Bank - Electrostatics  -  PhysicsISCE-Class 12-Question Bank - Electrostatics  -  Physics
ISCE-Class 12-Question Bank - Electrostatics - Physics
 
Hexadecimal to binary conversion
Hexadecimal to binary conversion Hexadecimal to binary conversion
Hexadecimal to binary conversion
 
Hexadecimal to decimal conversion
Hexadecimal to decimal conversion Hexadecimal to decimal conversion
Hexadecimal to decimal conversion
 
Hexadecimal to octal conversion
Hexadecimal to octal conversionHexadecimal to octal conversion
Hexadecimal to octal conversion
 
Gray code to binary conversion
Gray code to binary conversion Gray code to binary conversion
Gray code to binary conversion
 
What is Gray Code?
What is Gray Code? What is Gray Code?
What is Gray Code?
 
Decimal to Binary conversion
Decimal to Binary conversionDecimal to Binary conversion
Decimal to Binary conversion
 
Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21Video Lectures for IGCSE Physics 2020-21
Video Lectures for IGCSE Physics 2020-21
 
Refraction and dispersion of light through a prism
Refraction and dispersion of light through a prismRefraction and dispersion of light through a prism
Refraction and dispersion of light through a prism
 
Refraction of light at a plane surface
Refraction of light at a plane surfaceRefraction of light at a plane surface
Refraction of light at a plane surface
 
Spherical mirrors
Spherical mirrorsSpherical mirrors
Spherical mirrors
 
Atom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atomAtom, origin of spectra Bohr's theory of hydrogen atom
Atom, origin of spectra Bohr's theory of hydrogen atom
 
Refraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lensesRefraction of light at spherical surfaces of lenses
Refraction of light at spherical surfaces of lenses
 
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGEISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
ISCE (XII) - PHYSICS BOARD EXAM FEB 2020 - WEIGHTAGE
 
Cyber Laws
Cyber LawsCyber Laws
Cyber Laws
 
XML
XMLXML
XML
 

Último

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Último (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Ajax chap 2.-part 1

  • 1. Chap 3. Programming in Ajax 1 3. Programming in Ajax - Part I 1. Write program that asks the user to click a button, fetches data from a text file using Ajax techniques, and displays that data in the same web page without refreshing the whole page. The HTML file (AJAX1.HTML) is shown below: <html> <head> <title>Ajax at Work</title> <script language = "javascript"> var xhobj = false; if(window.XMLHttpRequest) { xhobj = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhobj = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID) { if(xhobj) { var obj = document.getElementById(divID); xhobj.open("GET", dataSource); xhobj.onreadystatechange = function() { if(xhobj.readyState == 4 && xhobj.status == 200) { obj.innerHTML = xhobj.responseText; } } xhobj.send(null); } } </script> </head> <body> <h1>Fetching data with Ajax</h1> <form> <input type = "button" value = "Display Message " onclick = "getData('http://localhost/AJAX/data.txt', 'targetDiv')"> </form> <div id = "targetDiv"> <p>The data fetched will go here</p> </div> </body> </html> The text file is data.txt and it has just one line in it: Hooray!! Hooray!! This is displayed by Ajax mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 2. 2 Programming in Ajax Analysis of the above program: 1. Consider the body of the HTML document. We display a button on this page by creating a <form> element. 2. We have also created a <div> element called “tartgetDiv” in which the fetched data will be displayed. 3. When the user clicks on this button, a JavaScript function called getData() is called. We use the onclick() event for this purpose. 4. The getData() function is passed 2 strings : a. The name of the text file DATA.TXT to fetch from the server, and a. The name of the <div> element to display the fetched text in. 5. In the <head> section of the HTML document we create the JavaScript code starting with the line : <script language = "javascript"> 6. Within the script, we create a variable to store the data, and an XMLHttpRequest object is created to set up a connection with the server and retrieve the data from the text file. 7. The code to create the XMLHttpRequest object is outside any function, so this code runs immediately as the page loads. 8. We create a variable for this object var xhobj = false; This variable is initialized to the value ‘false’ so that the script can check later whether the variable was created. 9. The XMLHttpRequest object is part of the browser’s window object. So to check whether the XMLHttpRequest object is ready to use, we use the if statement. If XMLHttpRequest object is available, we can create the object as follows, for non_IE browsers: if(window.XMLHttpRequest) { xhobj = new XMLHttpRequest(); } If we are working with Internet Explorer, we can create an XMLHttpRequest object like this: else if (window.ActiveXObject) { xhobj = new ActiveXObject("Microsoft.XMLHTTP"); } Now we have the XMLHttpRequest object. 10. The onreadystatechange property holds the name of the event handler that should be called when the value of the readyState property changes. 11. The readyState property holds the state of the request. 12. The getData() function will be used to actually fetch the text data from the file. 13. We first check that there is a valid object with the statement if (xhobj) 14. If the object creation hadn’t worked, then this variable will hold a value ‘false’ and the condition would become false. 15. Now we have the xhobj variable. This object has a method called “open()”. We will use that method to use the URL we want. Syntax of open() method is: open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]]) • method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD • URL – the requested URL • asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is ‘true’ (asynchronous) 16. The URL we want to fetch is passed to the getData() function as the dataSource argument 17. To open a URL we can use the GET, POST or PUT methods. But in this example we use the GET method. 18. Now, xhobj is ready to use the URL we have given. But it does not connect to that file. 19. By default the connection to this file is made asynchronously. It means that this statement does not wait until the connection is made and the data is finished downloading 20. The XMLHttpRequest object has a property called onreadystatechange that lets us handle asynchronous loading operations. 21. If we assign the name of a JavaScript function to this property, that function will be called each time the XMLHttpRequest object’s status changes. xhobj.onreadystatechange = function() 22. We have used a shortcut to assign a JavaScript function to the onreadystatechange property. We have created an anonymous function because the function does not have any name. Such a function is created on the fly, just by using the keyword function(). Then we define the body of this function in curly braces. This new anonymous function will be called whenever the XMLHttpRequest object undergoes a change. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 3. Chap 1. Introduction to Ajax 3 23. The XMLHttpRequest object has 2 properties that are important for us. The readyState property that tells us how the data downloading is progressing. The readyState property can have these values: 0 – uninitialized 1 – loading 2 – loaded 3 – interactive 4 – complete We have used the value 4, which means the data is downloaded. 24. The status property tells us the status of the download itself. It is the standard HTTP status code that the browser got for the URL we supplied. The possible values of status are: • 200 – all OK • 400 – Bad request • 403 – Forbidden • 404 – Not found • 408 – request time out • 414 – Requested URL too long So here is the meaning of the statement if(xhobj.readyState == 4 && xhobj.status == 200) It means we are checking that the data has been downloaded completely (readyState = 4) and everything went ok with the request to the server (status = 200) 25. The data has been fetched from the server. Now to get the data on the Web page we use one of these techniques: – If we want to treat the data as standard text, we use the object’s responseText property. – If the data is in XML format, we can use the responseXML property. 26. To make the test appear on the page, we assign that text to the <div> element whose ID is targetDiv. This ID was passed to the getData() function. 27. To connect to the server to get the response we use the send() method. When we are using the GET method, we send a value of null to connect to the server and request the data using the XMLHttpRequest object. xhobj.send(null); 28. The send() method actually downloads the data so that the anonymous function can handle that data. 2. Write a note on the XMLHttpRequest object. What are its properties and methods? 1. The XMLHttpRequest object is created to set up a connection with the server and retrieve the data from the text file from the web server without reloading the entire page. 2. This objet supports any text and XML formats. 3. It can be used to make requests over both HTTP and HTTPS protocols. 4. The XMLHttpRequest object is part of the browser’s window object. 5. We can create the XMLHttpRequest object as follows for non-IE browsers: if(window.XMLHttpRequest) { xhobj = new XMLHttpRequest(); } For IE browser, we create the XMLHttpRequest object as follows: if (window.ActiveXObject) { xhobj = new ActiveXObject("Microsoft.XMLHTTP"); } The first method shown above also works for IE 8 (yes, it has been tested by me!) Events of XMLHttpRequest object for Internet Explorer Property Description onreadystatechange Holds the name of the event holder that should be called when the value of the readyState property changes. ontimeout This event is raised when there is an error that prevents the completion of the request. mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 4. 4 Programming in Ajax Properties of XMLHttpRequest object for Internet Explorer Property Description readyState Holds the state of the request responseBody Holds a response body which is one way HTTP responses can be returned. responseStream Holds a response stream ( a binary stream) responseText Holds the response body as a string responseXML Holds the response body as XML Status Holds the HTTP status code returned by a request statusText Holds the HTTP response status text Timeout Gets or sets the timeout value. Methods of XMLHttpRequest object for Internet Explorer Method Description Abort Aborts the HTTP request getAllResponseHeaders Gets all the HTTP headers getResponseHeader Gets the value of an HTTP header Open Opens a request to a server Send Sends an HTTP request to the server setRequestHeader Sets the name and value of an HTTP header The open() method: Syntax: open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]]) • method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD • URL – the requested URL • asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is ‘true’ (asynchronous) The send() method: Syntax: object.send( [var]) This method is synchronous or asynchronous, depending on the value of the asyncFlag in the open method call. If asynchronous, this call returns immediately. The onreadystatechange event: This holds the name of the event holder that should be called when the value of the readyState property changes. The following script shows how to set an asynchronous event handler that alerts the user when the readyState property of the request reaches ‘complete’(value 4). xhobj.onreadystatechange = function() { if(xhobj.readyState == 4 && xhobj.status == 200) { alert('Transfer complete.'); } } The responseText property: It retrieves the response body as a string. It is a rad-only property and has no default value. Syntax sBody = object.responseText 3. What are the steps in creating an Ajax program? The various steps in creating an Ajax program are as follows: Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 5. Chap 1. Introduction to Ajax 5 1. Create an instance of the XMLHTTPRequest object that will work across different browser implementations. This object is part of the browser’s window. We create the object as follows: var xhobj = false; if(window.XMLHttpRequest) { xhobj = new XMLHttpRequest(); } 2. Prepare a request using the onreadystatechange event handler, the open method, and the send method. xhobj.onreadystatechange = function() 3. Process the response from the server through the properties readyState, status, responseText, and sometimes responseXML. if(xhobj.readyState == 4 && xhobj.status == 200) { obj.innerHTML = xhobj.responseText; } 4. How are asynchronous requests handled in Ajax? 1. The XMLHttpRequest object is the core of the Ajax engine. 2. It is the object that enables a page to get data from (using the GET method) or post data to (using the POST method) the server as a background request. 3. The browser is not refreshed during this process. 4. The XMLHttpRequest object eliminates the need to wait for the server to respond with a new page for each request. The user can continue to interact with the page while the requests are made in the background. 5. The most common formats in which we can receive data from XMLHttpRequest object is text or XML formats. 6. This object has a method called “open()”. We use that method to open the URL we want. Syntax of open() method is: open (“method”, “URL”, [,asyncFlag [, “username” [, “password”]]]) • method is the HTTP method used to open the connection such as GET, POST, PUT, HEAD • URL – the requested URL • asyncFlag – A boolean value indicating whether the call is asynchronous or synchronous. Default is ‘true’ (asynchronous) 5. Write a note on the XMLHttpRequest readyState property. The readyState property holds the status of the request sent by the client. This property has 4 possible values as follows: 0 – uninitialized: The object has been created but not initialized (i.e. the open () method has not been called) 1 – loading: Server connection has been established. A request has been opened but the send method has not been called. 2 – loaded: A request s received. The send method has been called. No data is available yet. 3 – interactive or processing request: A request has been opened. Some data is received but not all. 4 – complete or request finished and response is ready. This is a read-only property and it does not have a default value. When the value of this property becomes we can obtain the responseText property to obtain the text returned by the server. It is used along with the status property. 6. Write a note on the status property of the XMLHttpRequest object. The status property tells us the status of the download. It is the standard HTTP status code that the browser got for the URL we supplied. The possible values of status are: • 200 – all OK • 400 – Bad request • 403 – Forbidden • 404 – Not found • 408 – request time out • 414 – Requested URL too long To make sure that the data has been downloaded completely and everything went OK, we must check that the readyState property has the value 4 and the status property has the value 200. This is doe as follows: mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 6. 6 Programming in Ajax if(xhobj.readyState == 4 && xhobj.status == 200) { obj.innerHTML = xhobj.responseText; } 7. Explain the innerHTML property. 1. Each HTML element has an innerHTML property that defines both the code and the text that appears between the element’s opening and closing tags. 2. Before we can change the text that appears within the element tags, we must give an id (like a name) to this element. 3. Once the id has been given, we can use the getElementById function 4. The innerHTML property sets or returns the inner HTML of an element. 5. The innerHTML property can contain text and HTML elements. 6. When this property is set, the given string completely replaces the existing content of the object. 7. If the string contains HTML tags, the string is parsed and formatted. Example: <html> <head> <script type="text/javascript"> function changeText() { document.getElementById('boldStuff').innerHTML = "<font color='blue'>My Dearest Friends</font>"; } </script> </head> <body> <p>Welcome to the site <b id='boldStuff'>dude</b></p> <input type='button' onclick='changeText()' value='Change Text'/> </body> </html> 8. Write Ajax code to display three images on a web page. When the user moves the mouse over any image, the application fetches the text for that mouseover event using Ajax. We first create the HTML page AJAX2.HTML: <html> <head> <title>Ajax at Work</title> <script language = "javascript"> var xhr = false; if(window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID) { if(xhr) { var obj = document.getElementById(divID); xhr.open("GET", dataSource); xhr.onreadystatechange = function() Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 7. Chap 1. Introduction to Ajax 7 { if(xhr.readyState == 4 && xhr.status == 200) { obj.innerHTML = xhr.responseText; } } xhr.send(null); } } </script> </head> <body> <h1>Interactive Mouseovers</h1> <img src = "yahoo.jpg" onmouseover="getData('http://localhost/AJAX/yahoo.txt','targetDiv')"> <img src = "rediff.jpg" onmouseover="getData('http://localhost/AJAX/rediff.txt','targetDiv')"> <img src = "altavista.jpg" onmouseover="getData('http://localhost/AJAX/altavista.txt','targetDiv')"> <div id = "targetDiv"> <p>Search the web with these search engines</p> </div> </body> </html> The HTML file displays 3 images of three popular search engines in the <body> element. We connect the getData() function with the onmouseover() event. The getData function will fetch the text from the respective file. Next we create the 3 text files. The contents of each text file are shown: File:Altavista.txt, Content: <font color = 'red'>Altavista - was the king once upon a time</font> File:Rediff.txt, Content: Rediffmail portal - Recently main features have been updated. File:Yahoo.txt, Content: Yahoo portal - Mail, News, Chat, and more 9. What is server-side scripting? Which are the server-side scripting languages? 1. Server-side scripts are programs that can run on the server. 2. Normally when a browser requests an HTML file, the server returns the file, but if the file contains a server- side script, the script inside the HTML file is executed by the server before the file is returned to the browser as plain HTML. 3. Server-side scripts can do the following: a. Dynamically change the content of a web page b. Return data from a database mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 8. 8 Programming in Ajax c. Customize the web page so as to make it more useful; for the user. d. Provide security since the server-side code cannot be viewed from the browser. 4. The two common scripting languages are ASP and PHP. 10. Write the Ajax code that uses a PHP script on a server to display a message when the user clicks on a command button. The PHP file is DATA.PHP shown below: <?php echo ‘This text was fetched using Ajax.’; ?> The HTML file AJAX3.HTML is as follows: <html> <head> <title>Ajax and PHP at work</title> <script language = "javascript"> var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } function getData(dataSource, divID) { if(xhr) { var obj = document.getElementById(divID); xhr.open("GET", dataSource); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { obj.innerHTML = xhr.responseText; } } xhr.send(null); } } </script> </head> <body> <H1>Fetching data with Ajax and PHP</H1> <form> <input type = "button" value = "Display Message" onclick = "getData('data.php', 'targetDiv')"> </form> <div id="targetDiv"> <p>The fetched data will go here.</p> </div> </body> </html> Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 9. Chap 1. Introduction to Ajax 9 11. Write the code to show how to retrieve data from an XML document. Consider the following XML code in the AJAX5NOTE.XML: <note> <to>Raja </to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> The Ajax code to retrieve this XML file is as follows (AJAX5.HTML): <html> <head> <script type="text/javascript"> function loadXMLDoc(url) { if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.onreadystatechange=function() { if (xhr.readyState == 4 && xhr.status == 200) { document.getElementById('A1').innerHTML = xhr.status; document.getElementById('A2').innerHTML = xhr.statusText; document.getElementById('A3').innerHTML = xhr.responseText; } } xhr.open("GET", url, true); xhr.send(null); } </script> </head> <body> <h2>Retrieving data from XML file</h2> <p><b>Status: </b><span id="A1"></span></p> <p><b>Status text: </b><span id="A2"></span></p> <p><b>Response: </b><span id="A3"></span></p> <button onclick = "loadXMLDoc('/note.xml')"> Get XML data</button> </body> </html> mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 10. 10 Programming in Ajax 12. Explain the techniques by which Ajax passes data to the server. 1. Ajax can pass data to the server either by the GET or by the POST method. 2. If we use the GET method, the data sent is public as it can be seen in the browser’s address bar. This method uses URL encoding. It means that the data that is being sent is appended to the actual URL. 3. Suppose we have a text field named ‘a’ that contains the number 5, another text filed called ‘b’ that contains the text “centuries”, then all this data will be encoded and added to the URL. A question mark is ended to the end of the URL and data is added in the form name=value. Spaces are converted into a + sign and we separate the pairs of name=data by the ‘&’ sign. 4. So the complete URL becomes: www.servername.com/scriptname?a=5&b=centuries 5. All data sent this way is text, even if we send numbers. 6. The JavaScript escape function will encode data for appending to the end of the URL. This function will also convert spaces into the + symbol. 7. When we pass data to a URL by using the POST method, it is encoded internally and data is more secure. PROGRAMMING EXERCISES Modify the program in Q 1 so that it displays an alert box when the transfer of data is complete. Modify the following if statement as shown below: if(xhobj.readyState == 4 && xhobj.status == 200) { alert('Transfer complete.'); } Modify the program in Q 1 so that the page displays 2 command buttons. When the user clicks on the first button, the program fetches data from a file data1.txt. When the user clicks on the second command button, the program should fetch data from the file data2.txt and display that data in the same web page without refreshing the whole page. Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com