SlideShare a Scribd company logo
1 of 4
Download to read offline
Chap 5. Introducing Ajax Frameworks            1



                      5. Introducing Ajax Frameworks
 1.   What is Ajax framework? What are the advantages of using a framework?
      1. A framework is simply a reusable set of libraries or classes which simplify application
          development.
      2. Ajax framework is simply JavaScript files that that we can include in our own scripts. These
          JavaScript files contain JavaScript functions that we can call in our applications.
      3. These frameworks make coding easier and reduce the code development time. E.g., the
          programmer does not have to every time type out the syntax like ‘onreadystatechange’ and worry
          about spelling errors.
      4. To use the framework, we must include it in our script as follows: Suppose the framework is
          ajagold.js. We include it as follows:
              <script language = ‘text/javascript’ src = ‘ajaxgold.js’></script>
      Although these frameworks are for client-side coding, some Ajax frameworks also include a server-
      side component that enables database search and data manipulation.

 2.   Explain the working of the getDataReturnText function of the Ajax Gold library to fetch text
      from a file on the server. Explain the role of the callback function.
      The getDataReturnText function of the Ajax Gold library uses the GET method to get text from
      the server. Similarly, the function getDataReturnXml function is used to get XML file from the
      server.

      The general syntax of the getDataReturnText function is :
      getDataReturnText(url, callback);

      This function is passed two parameters: the url and the callback function. The function gets the
      text from the URL specified. This function in turn calls the function known as the ‘callback’ function.
      The callback function then receives the text.

      The getDataReturnText function is as follows:

      function getDataReturnText(url, callback)
      {
           var xhr = false;

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

              if(xhr)
              {
                   xhr.open("GET", url);

                      xhr.onreadystatechange = function()
                      {
                           if (xhr.readyState == 4 && xhr.status == 200)
                           {
                                 callback(xhr.responseText);

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


                                          delete xhr;
                                          xhr = null;
                                  }
                          }

               xhr.send(null);
              }
          }

          Now to use this function in our program, we create a HTML file called AJAX51.HTML:

          <html>
          <head>
          <title>Getting text with Ajax Gold</title>
          <script type = "text/javascript" src = "ajaxgold.js"></script>

          <script language = "javascript">
          function callback1(text)
          {
            document.getElementById("targetDiv").innerHTML =                          "Function 1 says"
                                                + text;
          }

          function callback2(text)
          {
            document.getElementById("targetDiv").innerHTML =                          "Function 2 says"
                                                + text;
          }
          </script>
          </head>

          <body>
          <H1>Getting text with Ajax Gold</H1>
          <form>
               <input type = "button" value = "Display Message"
                     onclick = "getDataReturnText('data51.txt', callback1)">
                <input type = "button" value = "Display Message 2"
                     onclick =   "getDataReturnText('data52.txt', callback2)">
          </form>

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

          We first load the Ajax Gold library by using this line:
          <script type = "text/javascript" src = "ajaxgold.js"></script>

          Each of the two buttons calls its own URL and has its own callback function to handle the text fetched
          from its URL.

     3.   Create a function getDataReturnXml to get XML data from the server.
          function getDataReturnXml(url, callback)

    Prof. Mukesh N Tekwani                                                   mukeshtekwani@hotmail.com
Chap 4. Ajax in Depth        3


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

             if(xhr)
             {
                  xhr.open("GET", url);

                     xhr.onreadystatechange = function()
                     {
                          if (xhr.readyState == 4 && xhr.status == 200)
                          {
                                callback(xhr.responseXML);
                                delete xhr;
                                xhr = null;
                          }
                     }
                     xhr.send(null);
             }
      }

 4.   Create a function postDataReturnText that uses the POST method to post (send) data to the
      server and get the text back from the server.
      The general syntax of the function postDataReturnText is as follows:
      postDataReturnText(url, data, callback);

      Here, we have to pass the URL, the data we want to post to the server and the callback function that
      will be passed the text obtained from the server. The POSt method is used to send data when
      confidentiality of data is important and also when large amount of data is to be sent.

      function postDataReturnText(url, data, callback)
      {
           var xhr = false;

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

             if(xhrMLHttpRequestObject)
             {
                  xhr.open("POST", url);
                  xhr.setRequestHeader('Content-Type',
                             'application/x-www-form-urlencoded');

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



                         xhr.onreadystatechange = function()
                         {
                              if (xhr.readyState == 4 && xhr.status == 200)
                              {
                                    callback(xhr.responseText);
                                    delete xhr;
                                    xhr = null;
                     }
                 }

                 XMLHttpRequestObject.send(data);
             }
         }




    Prof. Mukesh N Tekwani                                 mukeshtekwani@hotmail.com

More Related Content

What's hot

Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
MongoDB
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
MongoDB
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
MongoDB
 

What's hot (18)

Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8Reactive Access to MongoDB from Java 8
Reactive Access to MongoDB from Java 8
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
An introduction into Spring Data
An introduction into Spring DataAn introduction into Spring Data
An introduction into Spring Data
 
MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know MongoDB + Java - Everything you need to know
MongoDB + Java - Everything you need to know
 
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
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
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
 
Indexing & Query Optimization
Indexing & Query OptimizationIndexing & Query Optimization
Indexing & Query Optimization
 
Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!Data access 2.0? Please welcome: Spring Data!
Data access 2.0? Please welcome: Spring Data!
 
Advanced java practical semester 6_computer science
Advanced java practical semester 6_computer scienceAdvanced java practical semester 6_computer science
Advanced java practical semester 6_computer science
 
Indexing and Query Optimization
Indexing and Query OptimizationIndexing and Query Optimization
Indexing and Query Optimization
 
Java development with MongoDB
Java development with MongoDBJava development with MongoDB
Java development with MongoDB
 
Reducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQLReducing Development Time with MongoDB vs. SQL
Reducing Development Time with MongoDB vs. SQL
 
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
 
Asp.net server control
Asp.net  server controlAsp.net  server control
Asp.net server control
 
Symfony2 from the Trenches
Symfony2 from the TrenchesSymfony2 from the Trenches
Symfony2 from the Trenches
 

Viewers also liked

OSI Model - Every Detail Explained
OSI Model - Every Detail ExplainedOSI Model - Every Detail Explained
OSI Model - Every Detail Explained
Ashish Malik
 

Viewers also liked (12)

AJAX
AJAXAJAX
AJAX
 
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
 
Coding Ajax
Coding AjaxCoding Ajax
Coding Ajax
 
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 to Ajax chap 5

jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with Ajax
Wildan Maulana
 
Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8
anuradha raheja
 

Similar to Ajax chap 5 (20)

jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
Ajax
AjaxAjax
Ajax
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
JavaScript Lessons 2023
JavaScript Lessons 2023JavaScript Lessons 2023
JavaScript Lessons 2023
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
 
J query 01.07.2013.html
J query 01.07.2013.htmlJ query 01.07.2013.html
J query 01.07.2013.html
 
J query 01.07.2013
J query 01.07.2013J query 01.07.2013
J query 01.07.2013
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8Ajaxtechnicalworkshopshortversion 1224845432835700-8
Ajaxtechnicalworkshopshortversion 1224845432835700-8
 
Ajax cheat sheet
Ajax cheat sheetAjax cheat sheet
Ajax cheat sheet
 
Ajax Tuturial
Ajax TuturialAjax Tuturial
Ajax Tuturial
 
Xml http request
Xml http requestXml http request
Xml http request
 
Lec 7
Lec 7Lec 7
Lec 7
 
Ajax - a quick introduction
Ajax - a quick introductionAjax - a quick introduction
Ajax - a quick introduction
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Ajax
AjaxAjax
Ajax
 

More from Mukesh Tekwani

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

Recently uploaded

The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
heathfieldcps1
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
QucHHunhnh
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
QucHHunhnh
 

Recently uploaded (20)

ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701ComPTIA Overview | Comptia Security+ Book SY0-701
ComPTIA Overview | Comptia Security+ Book SY0-701
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural ResourcesEnergy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
Energy Resources. ( B. Pharmacy, 1st Year, Sem-II) Natural Resources
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-IIFood Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
Food Chain and Food Web (Ecosystem) EVS, B. Pharmacy 1st Year, Sem-II
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Sociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning ExhibitSociology 101 Demonstration of Learning Exhibit
Sociology 101 Demonstration of Learning Exhibit
 
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
Ecological Succession. ( ECOSYSTEM, B. Pharmacy, 1st Year, Sem-II, Environmen...
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17  How to Extend Models Using Mixin ClassesMixin Classes in Odoo 17  How to Extend Models Using Mixin Classes
Mixin Classes in Odoo 17 How to Extend Models Using Mixin Classes
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 

Ajax chap 5

  • 1. Chap 5. Introducing Ajax Frameworks 1 5. Introducing Ajax Frameworks 1. What is Ajax framework? What are the advantages of using a framework? 1. A framework is simply a reusable set of libraries or classes which simplify application development. 2. Ajax framework is simply JavaScript files that that we can include in our own scripts. These JavaScript files contain JavaScript functions that we can call in our applications. 3. These frameworks make coding easier and reduce the code development time. E.g., the programmer does not have to every time type out the syntax like ‘onreadystatechange’ and worry about spelling errors. 4. To use the framework, we must include it in our script as follows: Suppose the framework is ajagold.js. We include it as follows: <script language = ‘text/javascript’ src = ‘ajaxgold.js’></script> Although these frameworks are for client-side coding, some Ajax frameworks also include a server- side component that enables database search and data manipulation. 2. Explain the working of the getDataReturnText function of the Ajax Gold library to fetch text from a file on the server. Explain the role of the callback function. The getDataReturnText function of the Ajax Gold library uses the GET method to get text from the server. Similarly, the function getDataReturnXml function is used to get XML file from the server. The general syntax of the getDataReturnText function is : getDataReturnText(url, callback); This function is passed two parameters: the url and the callback function. The function gets the text from the URL specified. This function in turn calls the function known as the ‘callback’ function. The callback function then receives the text. The getDataReturnText function is as follows: function getDataReturnText(url, callback) { var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if(xhr) { xhr.open("GET", url); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { callback(xhr.responseText); mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 2. 2 Ajax in Depth delete xhr; xhr = null; } } xhr.send(null); } } Now to use this function in our program, we create a HTML file called AJAX51.HTML: <html> <head> <title>Getting text with Ajax Gold</title> <script type = "text/javascript" src = "ajaxgold.js"></script> <script language = "javascript"> function callback1(text) { document.getElementById("targetDiv").innerHTML = "Function 1 says" + text; } function callback2(text) { document.getElementById("targetDiv").innerHTML = "Function 2 says" + text; } </script> </head> <body> <H1>Getting text with Ajax Gold</H1> <form> <input type = "button" value = "Display Message" onclick = "getDataReturnText('data51.txt', callback1)"> <input type = "button" value = "Display Message 2" onclick = "getDataReturnText('data52.txt', callback2)"> </form> <div id="targetDiv"> <p>The fetched data will go here.</p> </div> </body> </html> We first load the Ajax Gold library by using this line: <script type = "text/javascript" src = "ajaxgold.js"></script> Each of the two buttons calls its own URL and has its own callback function to handle the text fetched from its URL. 3. Create a function getDataReturnXml to get XML data from the server. function getDataReturnXml(url, callback) Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com
  • 3. Chap 4. Ajax in Depth 3 { var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if(xhr) { xhr.open("GET", url); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { callback(xhr.responseXML); delete xhr; xhr = null; } } xhr.send(null); } } 4. Create a function postDataReturnText that uses the POST method to post (send) data to the server and get the text back from the server. The general syntax of the function postDataReturnText is as follows: postDataReturnText(url, data, callback); Here, we have to pass the URL, the data we want to post to the server and the callback function that will be passed the text obtained from the server. The POSt method is used to send data when confidentiality of data is important and also when large amount of data is to be sent. function postDataReturnText(url, data, callback) { var xhr = false; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { Xhr = new ActiveXObject("Microsoft.XMLHTTP"); } if(xhrMLHttpRequestObject) { xhr.open("POST", url); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); mukeshtekwani@hotmail.com Prof. Mukesh N. Tekwani
  • 4. 4 Ajax in Depth xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { callback(xhr.responseText); delete xhr; xhr = null; } } XMLHttpRequestObject.send(data); } } Prof. Mukesh N Tekwani mukeshtekwani@hotmail.com