SlideShare uma empresa Scribd logo
1 de 27
Baixar para ler offline
-By V.Gouthaman
INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.
Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.
ASYNCHRONOUS REQUEST AND RESPONSE
The Anatomy of an Ajax Interaction Let's consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the Ajax interaction that will provide the validation logic.
 
[object Object],[object Object],[object Object]
<input type=&quot;text&quot; size=&quot;20&quot;  id=&quot;userid&quot; name=&quot;id&quot; onkeyup=&quot;validate();&quot;> This form element will call the validate() function each time the user presses a key in the form field.
2. A XMLHttpRequest object is created and configured. An XMLHttpRequest object is created and configured.  var req; function validate() { var idField = document.getElementById(&quot;userid&quot;); var url = &quot;validate?id=&quot; + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != &quot;undefined&quot;) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } req.open(&quot;GET&quot;, url, true); req.onreadystatechange = callback; req.send(null); }
The validate() function creates an XMLHttpRequest object and calls the open function on the object. The open function requires three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously. The API is XMLHttpRequest.open(String method, String URL, boolean asynchronous). If an interaction is set as asynchronous (true) a callback function must be specified. The callback function for this interaction is set with the statement req.onreadystatechange = callback;. See section 6 for more details.
3. The XMLHttpRequest object makes a call. When the statement req.send(null); is reached, the call will be made. In the case of an HTTP GET, this content may be null or left blank. When this function is called on the XMLHttpRequest object, the call to the URL that was set during the configuration of the object is called. In the case of this example, the data that is posted (id) is included as a URL parameter.  Use an HTTP GET when the request is idempotent, meaning that two duplicate requests will return the same results. When using the HTTP GET method, the length of URL, including escaped URL parameters, is limited by some browsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will affect the server-side application state. An HTTP POST requires a Content-Type header to be set on the XMLHttpRequest object by using the following statement:
req.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); req.send(&quot;id=&quot; + encodeURIComponent(idTextField.value)); When sending form values from JavaScript technology, you should take into consideration the encoding of the field values. JavaScript technology includes an encodeURIComponent() function that should be used to ensure that localized content is encoded properly and that special characters are encoded correctly to be passed in an HTTP request.
4. The request is processed by the ValidateServlet. A servlet mapped to the URI &quot;validate&quot; checks whether the user ID is in the user database.A servlet processes an XMLHttpRequest just as it would any other HTTP request. The following example show a server extracting the id parameter from the request and validating whether the parameter has been taken.  public class ValidateServlet extends  HttpServlet { private ServletContext context;   private HashMap users = new HashMap(); public void init(ServletConfig config) throws ServletException { super.init(config); this.context = config.getServletContext(); users.put(&quot;greg&quot;,&quot;account data&quot;); users.put(&quot;duke&quot;,&quot;account data&quot;); }
public void doGet(HttpServletRequest request, HttpServletResponse  response) throws IOException, ServletException { String targetId = request.getParameter(&quot;id&quot;); if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>valid</message>&quot;);  } else  { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;);  } } } In this example, a simple HashMap is used to contain the users. In the case of this example, let us assume that the user typed duke as the ID.
5. The ValidateServlet returns an XML document containing the results. The user ID duke is present in the list of user IDs in the users HashMap. The ValidateServlet will write an XML document to the response containing a message element with the value of invalid. More complex usecases may require DOM, XSLT, or other APIs to generate the  response.response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;)
6. The XMLHttpRequest object calls the callback() function and processes the result. The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction. function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid } } }
Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded. Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now let's look at how to use the DOM APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet.
<message> valid </message> This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user: function parseMessage() { var message = req.responseXML.getElementsByTagName(&quot;message&quot;)[0]; setMessage(message.childNodes[0].nodeValue); } The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.
7. The HTML DOM is updated. JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById(&quot;userIdMessage&quot;), where &quot;userIdMessage&quot; is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements.  One common means to change the body content of an element is to set the innerHTML property on the element as in the following example.
<script type=&quot;text/javascript&quot;> ... function setMessage(message) { var mdiv = document.getElementById(&quot;userIdMessage&quot;); if (message == &quot;invalid&quot;) { mdiv.innerHTML = &quot;<div style=amp;quot;color:redamp;quot;>Invalid User Id</ div>&quot;; } else { mdiv.innerHTML = &quot;<div style=amp;quot;color:greenamp;quot;>Valid User Id</ div>&quot;; } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body>
The portions of the HTML page that were affected are re-rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as <image> or <iframe>, the content specified by those elements is fetched and rendered as well. Ajax applications such as Google Maps use this technique of adding image elements using Ajax calls to dynamically build maps. The main drawback with this approach is that HTML elements are hardcoded as strings in the JavaScript technology code. Hardcoding HTML markup inside JavaScript technology code is not a good practice because it makes the code difficult to read, maintain, and modify. Consider using the JavaScript technology DOM APIs to create or modify HTML elements within JavaScript technology code. Intermixing presentation with JavaScript technology code as strings will make a page difficult to read and edit. Another means of modifying the HTML DOM is to dynamically create new elements and append them as children to a target element as in the following example.
<script type=&quot;text/javascript&quot;> ... function setMessage(message) { var userMessageElement = document.getElementById(&quot;userIdMessage&quot;); var messageText; if (message == &quot;invalid&quot;) { userMessageElement.style.color = &quot;red&quot;; messageText = &quot;Invalid User Id&quot;; } else { userMessageElement.style.color = &quot;green&quot;; messageText = &quot;Valid User Id&quot;; }  var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple replace it otherwise
// append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody,  userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body> The code sample shows how JavaScript technology DOM APIs may be used to create an element or alter the element programmatically. The support for JavaScript technology DOM APIs can differ in various browsers, so you must take care when developing applications.
What is the main strength of AJAX? Or why and when should we use AJAX in web application? ,[object Object],[object Object]
In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so. Here is a simple example – function check() { var a=0; a = getStatus(“getstatus.php?id=5”); if(a==1) { alert(“active”); } else { alert(“not active”); } }
Here getStatus() function sends a AJAX request to the server with “getstatus.php?id=5” url and the php file decides (from database may be) the status and output/response as 1 or 0. But, this function will not work properly. It will alert “not active” instead of “active”. And yes, that is for the asynchronous request. The reason is – when a = getStatus(“getstatus.php?id=5”); line is being executed program does not wait for the response of setStatus() function. So, value of keep unchanged or set to null. So, how should we work with asynchronous request? Of course, using callback function. Callback function is that function which is triggered when the request completes to get the response (or as defined).
 

Mais conteúdo relacionado

Mais procurados

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Securityamiable_indian
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CStutorialsruby
 
Academy PRO: ASP .NET Core MVC
Academy PRO: ASP .NET Core MVCAcademy PRO: ASP .NET Core MVC
Academy PRO: ASP .NET Core MVCBinary Studio
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationMicha Kops
 
My Portfolio
My PortfolioMy Portfolio
My Portfolioaemartin4
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB
 
Programming web application
Programming web applicationProgramming web application
Programming web applicationaspnet123
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applicationsAlex Golesh
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injectionMickey Jack
 

Mais procurados (17)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Pascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax SecurityPascarello_Investigating JavaScript and Ajax Security
Pascarello_Investigating JavaScript and Ajax Security
 
ASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CSASPNET_MVC_Tutorial_06_CS
ASPNET_MVC_Tutorial_06_CS
 
Academy PRO: ASP .NET Core MVC
Academy PRO: ASP .NET Core MVCAcademy PRO: ASP .NET Core MVC
Academy PRO: ASP .NET Core MVC
 
Creating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat ApplicationCreating a Java EE 7 Websocket Chat Application
Creating a Java EE 7 Websocket Chat Application
 
Data Binding
Data BindingData Binding
Data Binding
 
State management
State managementState management
State management
 
J2EE jsp_03
J2EE jsp_03J2EE jsp_03
J2EE jsp_03
 
My Portfolio
My PortfolioMy Portfolio
My Portfolio
 
AJAX
AJAXAJAX
AJAX
 
MongoDB Stitch Tutorial
MongoDB Stitch TutorialMongoDB Stitch Tutorial
MongoDB Stitch Tutorial
 
Programming web application
Programming web applicationProgramming web application
Programming web application
 
Windows 8 metro applications
Windows 8 metro applicationsWindows 8 metro applications
Windows 8 metro applications
 
Understanding AJAX
Understanding AJAXUnderstanding AJAX
Understanding AJAX
 
Asp db
Asp dbAsp db
Asp db
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
Remote code-with-expression-language-injection
Remote code-with-expression-language-injectionRemote code-with-expression-language-injection
Remote code-with-expression-language-injection
 

Destaque

Answers for 2 Marks Unit Test I (RMW)
Answers for 2 Marks Unit Test I (RMW)Answers for 2 Marks Unit Test I (RMW)
Answers for 2 Marks Unit Test I (RMW)Gouthaman V
 
Méthode d'Agile: Scrum
Méthode d'Agile: ScrumMéthode d'Agile: Scrum
Méthode d'Agile: ScrumChaymaMghazli
 
VI Semester Examination Time Table
VI Semester Examination Time TableVI Semester Examination Time Table
VI Semester Examination Time TableGouthaman V
 
Antenna Unit Test II questions
Antenna Unit Test II questionsAntenna Unit Test II questions
Antenna Unit Test II questionsGouthaman V
 
Antenna Unit Test II Questions
Antenna Unit Test II QuestionsAntenna Unit Test II Questions
Antenna Unit Test II QuestionsGouthaman V
 

Destaque (7)

Answers for 2 Marks Unit Test I (RMW)
Answers for 2 Marks Unit Test I (RMW)Answers for 2 Marks Unit Test I (RMW)
Answers for 2 Marks Unit Test I (RMW)
 
Web 2.0
Web 2.0Web 2.0
Web 2.0
 
HTML
HTMLHTML
HTML
 
Méthode d'Agile: Scrum
Méthode d'Agile: ScrumMéthode d'Agile: Scrum
Méthode d'Agile: Scrum
 
VI Semester Examination Time Table
VI Semester Examination Time TableVI Semester Examination Time Table
VI Semester Examination Time Table
 
Antenna Unit Test II questions
Antenna Unit Test II questionsAntenna Unit Test II questions
Antenna Unit Test II questions
 
Antenna Unit Test II Questions
Antenna Unit Test II QuestionsAntenna Unit Test II Questions
Antenna Unit Test II Questions
 

Semelhante a AJAX

Semelhante a AJAX (20)

ajax_pdf
ajax_pdfajax_pdf
ajax_pdf
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Core Java tutorial at Unit Nexus
Core Java tutorial at Unit NexusCore Java tutorial at Unit Nexus
Core Java tutorial at Unit Nexus
 
jQuery : Talk to server with Ajax
jQuery : Talk to server with AjaxjQuery : Talk to server with Ajax
jQuery : Talk to server with Ajax
 
Ajax presentation
Ajax presentationAjax presentation
Ajax presentation
 
Ajax
AjaxAjax
Ajax
 
Ajax Introduction
Ajax IntroductionAjax Introduction
Ajax Introduction
 
Ajax
AjaxAjax
Ajax
 
Ajax ppt
Ajax pptAjax ppt
Ajax ppt
 
Ajax Ppt
Ajax PptAjax Ppt
Ajax Ppt
 
RicoAjaxEngine
RicoAjaxEngineRicoAjaxEngine
RicoAjaxEngine
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Ajax.ppt
Ajax.pptAjax.ppt
Ajax.ppt
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
Ajax
AjaxAjax
Ajax
 
jQuery - Chapter 5 - Ajax
jQuery - Chapter 5 -  AjaxjQuery - Chapter 5 -  Ajax
jQuery - Chapter 5 - Ajax
 
AJAX Workshop Notes
AJAX Workshop NotesAJAX Workshop Notes
AJAX Workshop Notes
 

Mais de Gouthaman V

Professional Ethics Assignment II
Professional Ethics Assignment IIProfessional Ethics Assignment II
Professional Ethics Assignment IIGouthaman V
 
Scholastic averages sheet-2
Scholastic averages sheet-2Scholastic averages sheet-2
Scholastic averages sheet-2Gouthaman V
 
Eligibility criteria and instructions for Infosys Placement
Eligibility criteria and instructions for Infosys PlacementEligibility criteria and instructions for Infosys Placement
Eligibility criteria and instructions for Infosys PlacementGouthaman V
 
Anwers for 2 marks - RMW
Anwers for 2 marks - RMWAnwers for 2 marks - RMW
Anwers for 2 marks - RMWGouthaman V
 
Rmw unit test question papers
Rmw unit test question papersRmw unit test question papers
Rmw unit test question papersGouthaman V
 
Circular and semicircular cavity resonator
Circular and semicircular cavity resonatorCircular and semicircular cavity resonator
Circular and semicircular cavity resonatorGouthaman V
 
VLSI Anna University Practical Examination
VLSI Anna University Practical ExaminationVLSI Anna University Practical Examination
VLSI Anna University Practical ExaminationGouthaman V
 
VLSI Sequential Circuits II
VLSI Sequential Circuits IIVLSI Sequential Circuits II
VLSI Sequential Circuits IIGouthaman V
 
Antenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment IAntenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment IGouthaman V
 
Antenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment IAntenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment IGouthaman V
 
Computer Networks Unit Test II Questions
Computer Networks Unit Test II QuestionsComputer Networks Unit Test II Questions
Computer Networks Unit Test II QuestionsGouthaman V
 
Sequential Circuits I VLSI 9th experiment
Sequential Circuits I VLSI 9th experimentSequential Circuits I VLSI 9th experiment
Sequential Circuits I VLSI 9th experimentGouthaman V
 
Combinational circuits II outputs
Combinational circuits II outputsCombinational circuits II outputs
Combinational circuits II outputsGouthaman V
 
POM Unit Test II - ECE B
POM Unit Test II - ECE BPOM Unit Test II - ECE B
POM Unit Test II - ECE BGouthaman V
 
All VLSI programs
All VLSI programsAll VLSI programs
All VLSI programsGouthaman V
 
VLSI experiments II
VLSI experiments IIVLSI experiments II
VLSI experiments IIGouthaman V
 
VLSI Experiments I
VLSI Experiments IVLSI Experiments I
VLSI Experiments IGouthaman V
 

Mais de Gouthaman V (20)

Professional Ethics Assignment II
Professional Ethics Assignment IIProfessional Ethics Assignment II
Professional Ethics Assignment II
 
Dip Unit Test-I
Dip Unit Test-IDip Unit Test-I
Dip Unit Test-I
 
Scholastic averages sheet-2
Scholastic averages sheet-2Scholastic averages sheet-2
Scholastic averages sheet-2
 
Eligibility criteria and instructions for Infosys Placement
Eligibility criteria and instructions for Infosys PlacementEligibility criteria and instructions for Infosys Placement
Eligibility criteria and instructions for Infosys Placement
 
Anwers for 2 marks - RMW
Anwers for 2 marks - RMWAnwers for 2 marks - RMW
Anwers for 2 marks - RMW
 
Rmw unit test question papers
Rmw unit test question papersRmw unit test question papers
Rmw unit test question papers
 
Circular and semicircular cavity resonator
Circular and semicircular cavity resonatorCircular and semicircular cavity resonator
Circular and semicircular cavity resonator
 
VLSI Anna University Practical Examination
VLSI Anna University Practical ExaminationVLSI Anna University Practical Examination
VLSI Anna University Practical Examination
 
HCL IPT
HCL IPTHCL IPT
HCL IPT
 
VLSI Sequential Circuits II
VLSI Sequential Circuits IIVLSI Sequential Circuits II
VLSI Sequential Circuits II
 
Email
EmailEmail
Email
 
Antenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment IAntenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment I
 
Antenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment IAntenna and Wave Propagation Assignment I
Antenna and Wave Propagation Assignment I
 
Computer Networks Unit Test II Questions
Computer Networks Unit Test II QuestionsComputer Networks Unit Test II Questions
Computer Networks Unit Test II Questions
 
Sequential Circuits I VLSI 9th experiment
Sequential Circuits I VLSI 9th experimentSequential Circuits I VLSI 9th experiment
Sequential Circuits I VLSI 9th experiment
 
Combinational circuits II outputs
Combinational circuits II outputsCombinational circuits II outputs
Combinational circuits II outputs
 
POM Unit Test II - ECE B
POM Unit Test II - ECE BPOM Unit Test II - ECE B
POM Unit Test II - ECE B
 
All VLSI programs
All VLSI programsAll VLSI programs
All VLSI programs
 
VLSI experiments II
VLSI experiments IIVLSI experiments II
VLSI experiments II
 
VLSI Experiments I
VLSI Experiments IVLSI Experiments I
VLSI Experiments I
 

Último

How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17Celine George
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfTechSoup
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfMohonDas
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxSaurabhParmar42
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17Celine George
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRATanmoy Mishra
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesCeline George
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxiammrhaywood
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxKatherine Villaluna
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxKatherine Villaluna
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxraviapr7
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxMYDA ANGELICA SUAN
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptxraviapr7
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxraviapr7
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptxSandy Millin
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsEugene Lysak
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.EnglishCEIPdeSigeiro
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesMohammad Hassany
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfMohonDas
 

Último (20)

How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17How to Use api.constrains ( ) in Odoo 17
How to Use api.constrains ( ) in Odoo 17
 
UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024UKCGE Parental Leave Discussion March 2024
UKCGE Parental Leave Discussion March 2024
 
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdfMaximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
Maximizing Impact_ Nonprofit Website Planning, Budgeting, and Design.pdf
 
Diploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdfDiploma in Nursing Admission Test Question Solution 2023.pdf
Diploma in Nursing Admission Test Question Solution 2023.pdf
 
CAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptxCAULIFLOWER BREEDING 1 Parmar pptx
CAULIFLOWER BREEDING 1 Parmar pptx
 
How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17How to Add a many2many Relational Field in Odoo 17
How to Add a many2many Relational Field in Odoo 17
 
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRADUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
DUST OF SNOW_BY ROBERT FROST_EDITED BY_ TANMOY MISHRA
 
How to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 SalesHow to Manage Cross-Selling in Odoo 17 Sales
How to Manage Cross-Selling in Odoo 17 Sales
 
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptxAUDIENCE THEORY -- FANDOM -- JENKINS.pptx
AUDIENCE THEORY -- FANDOM -- JENKINS.pptx
 
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptxPractical Research 1: Lesson 8 Writing the Thesis Statement.pptx
Practical Research 1: Lesson 8 Writing the Thesis Statement.pptx
 
Practical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptxPractical Research 1 Lesson 9 Scope and delimitation.pptx
Practical Research 1 Lesson 9 Scope and delimitation.pptx
 
Prescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptxPrescribed medication order and communication skills.pptx
Prescribed medication order and communication skills.pptx
 
Patterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptxPatterns of Written Texts Across Disciplines.pptx
Patterns of Written Texts Across Disciplines.pptx
 
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptxClinical Pharmacy  Introduction to Clinical Pharmacy, Concept of clinical pptx
Clinical Pharmacy Introduction to Clinical Pharmacy, Concept of clinical pptx
 
Education and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptxEducation and training program in the hospital APR.pptx
Education and training program in the hospital APR.pptx
 
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
2024.03.23 What do successful readers do - Sandy Millin for PARK.pptx
 
The Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George WellsThe Stolen Bacillus by Herbert George Wells
The Stolen Bacillus by Herbert George Wells
 
Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.Easter in the USA presentation by Chloe.
Easter in the USA presentation by Chloe.
 
Human-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming ClassesHuman-AI Co-Creation of Worked Examples for Programming Classes
Human-AI Co-Creation of Worked Examples for Programming Classes
 
HED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdfHED Office Sohayok Exam Question Solution 2023.pdf
HED Office Sohayok Exam Question Solution 2023.pdf
 

AJAX

  • 2. INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create interactive web applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.
  • 3. Like DHTML and LAMP, Ajax is not a technology in itself, but a group of technologies. Ajax uses a combination of HTML and CSS to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.
  • 5. The Anatomy of an Ajax Interaction Let's consider an example. A web application contains a static HTML page, or an HTML page generated in JSP technology contains an HTML form that requires server-side logic to validate form data without refreshing the page. A server-side web component (servlet) named ValidateServlet will provide the validation logic. Figure 1 describes the details of the Ajax interaction that will provide the validation logic.
  • 6.  
  • 7.
  • 8. <input type=&quot;text&quot; size=&quot;20&quot; id=&quot;userid&quot; name=&quot;id&quot; onkeyup=&quot;validate();&quot;> This form element will call the validate() function each time the user presses a key in the form field.
  • 9. 2. A XMLHttpRequest object is created and configured. An XMLHttpRequest object is created and configured. var req; function validate() { var idField = document.getElementById(&quot;userid&quot;); var url = &quot;validate?id=&quot; + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != &quot;undefined&quot;) { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;); } req.open(&quot;GET&quot;, url, true); req.onreadystatechange = callback; req.send(null); }
  • 10. The validate() function creates an XMLHttpRequest object and calls the open function on the object. The open function requires three arguments: the HTTP method, which is GET or POST; the URL of the server-side component that the object will interact with; and a boolean indicating whether or not the call will be made asynchronously. The API is XMLHttpRequest.open(String method, String URL, boolean asynchronous). If an interaction is set as asynchronous (true) a callback function must be specified. The callback function for this interaction is set with the statement req.onreadystatechange = callback;. See section 6 for more details.
  • 11. 3. The XMLHttpRequest object makes a call. When the statement req.send(null); is reached, the call will be made. In the case of an HTTP GET, this content may be null or left blank. When this function is called on the XMLHttpRequest object, the call to the URL that was set during the configuration of the object is called. In the case of this example, the data that is posted (id) is included as a URL parameter. Use an HTTP GET when the request is idempotent, meaning that two duplicate requests will return the same results. When using the HTTP GET method, the length of URL, including escaped URL parameters, is limited by some browsers and by server-side web containers. The HTTP POST method should be used when sending data to the server that will affect the server-side application state. An HTTP POST requires a Content-Type header to be set on the XMLHttpRequest object by using the following statement:
  • 12. req.setRequestHeader(&quot;Content-Type&quot;, &quot;application/x-www-form-urlencoded&quot;); req.send(&quot;id=&quot; + encodeURIComponent(idTextField.value)); When sending form values from JavaScript technology, you should take into consideration the encoding of the field values. JavaScript technology includes an encodeURIComponent() function that should be used to ensure that localized content is encoded properly and that special characters are encoded correctly to be passed in an HTTP request.
  • 13. 4. The request is processed by the ValidateServlet. A servlet mapped to the URI &quot;validate&quot; checks whether the user ID is in the user database.A servlet processes an XMLHttpRequest just as it would any other HTTP request. The following example show a server extracting the id parameter from the request and validating whether the parameter has been taken. public class ValidateServlet extends HttpServlet { private ServletContext context; private HashMap users = new HashMap(); public void init(ServletConfig config) throws ServletException { super.init(config); this.context = config.getServletContext(); users.put(&quot;greg&quot;,&quot;account data&quot;); users.put(&quot;duke&quot;,&quot;account data&quot;); }
  • 14. public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter(&quot;id&quot;); if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>valid</message>&quot;); } else { response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;); } } } In this example, a simple HashMap is used to contain the users. In the case of this example, let us assume that the user typed duke as the ID.
  • 15. 5. The ValidateServlet returns an XML document containing the results. The user ID duke is present in the list of user IDs in the users HashMap. The ValidateServlet will write an XML document to the response containing a message element with the value of invalid. More complex usecases may require DOM, XSLT, or other APIs to generate the response.response.setContentType(&quot;text/xml&quot;); response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;); response.getWriter().write(&quot;<message>invalid</message>&quot;)
  • 16. 6. The XMLHttpRequest object calls the callback() function and processes the result. The XMLHttpRequest object was configured to call the callback() function when there are changes to the readyState of the XMLHttpRequest object. Let us assume the call to the ValidateServlet was made and the readyState is 4, signifying the XMLHttpRequest call is complete. The HTTP status code of 200 signifies a successful HTTP interaction. function callback() { if (req.readyState == 4) { if (req.status == 200) { // update the HTML DOM based on whether or not message is valid } } }
  • 17. Browsers maintain an object representation of the documents being displayed (referred to as the Document Object Model or DOM). JavaScript technology in an HTML page has access to the DOM, and APIs are available that allow JavaScript technology to modify the DOM after the page has loaded. Following a successful request, JavaScript technology code may modify the DOM of the HTML page. The object representation of the XML document that was retrieved from the ValidateServlet is available to JavaScript technology code using the req.responseXML, where req is an XMLHttpRequest object. The DOM APIs provide a means for JavaScript technology to navigate the content from that document and use that content to modify the DOM of the HTML page. The string representation of the XML document that was returned may be accessed by calling req.responseText. Now let's look at how to use the DOM APIs in JavaScript technology by looking at the following XML document returned from the ValidateServlet.
  • 18. <message> valid </message> This example is a simple XML fragment that contains the sender of the message element, which is simply the string valid or invalid. A more advanced sample may contain more than one message and valid names that might be presented to the user: function parseMessage() { var message = req.responseXML.getElementsByTagName(&quot;message&quot;)[0]; setMessage(message.childNodes[0].nodeValue); } The parseMessages() function will process an XML document retrieved from the ValidateServlet. This function will call the setMessage() with the value of the message element to update the HTML DOM.
  • 19. 7. The HTML DOM is updated. JavaScript technology can gain a reference to any element in the HTML DOM using a number of APIs. The recommended way to gain a reference to an element is to call document.getElementById(&quot;userIdMessage&quot;), where &quot;userIdMessage&quot; is the ID attribute of an element appearing in the HTML document. With a reference to the element, JavaScript technology may now be used to modify the element's attributes; modify the element's style properties; or add, remove, or modify child elements. One common means to change the body content of an element is to set the innerHTML property on the element as in the following example.
  • 20. <script type=&quot;text/javascript&quot;> ... function setMessage(message) { var mdiv = document.getElementById(&quot;userIdMessage&quot;); if (message == &quot;invalid&quot;) { mdiv.innerHTML = &quot;<div style=amp;quot;color:redamp;quot;>Invalid User Id</ div>&quot;; } else { mdiv.innerHTML = &quot;<div style=amp;quot;color:greenamp;quot;>Valid User Id</ div>&quot;; } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body>
  • 21. The portions of the HTML page that were affected are re-rendered immediately following the setting of the innerHTML. If the innerHTML property contains elements such as <image> or <iframe>, the content specified by those elements is fetched and rendered as well. Ajax applications such as Google Maps use this technique of adding image elements using Ajax calls to dynamically build maps. The main drawback with this approach is that HTML elements are hardcoded as strings in the JavaScript technology code. Hardcoding HTML markup inside JavaScript technology code is not a good practice because it makes the code difficult to read, maintain, and modify. Consider using the JavaScript technology DOM APIs to create or modify HTML elements within JavaScript technology code. Intermixing presentation with JavaScript technology code as strings will make a page difficult to read and edit. Another means of modifying the HTML DOM is to dynamically create new elements and append them as children to a target element as in the following example.
  • 22. <script type=&quot;text/javascript&quot;> ... function setMessage(message) { var userMessageElement = document.getElementById(&quot;userIdMessage&quot;); var messageText; if (message == &quot;invalid&quot;) { userMessageElement.style.color = &quot;red&quot;; messageText = &quot;Invalid User Id&quot;; } else { userMessageElement.style.color = &quot;green&quot;; messageText = &quot;Valid User Id&quot;; } var messageBody = document.createTextNode(messageText); // if the messageBody element has been created simple replace it otherwise
  • 23. // append the new element if (userMessageElement.childNodes[0]) { userMessageElement.replaceChild(messageBody, userMessageElement.childNodes[0]); } else { userMessageElement.appendChild(messageBody); } } </script> <body> <div id=&quot;userIdMessage&quot;></div> </body> The code sample shows how JavaScript technology DOM APIs may be used to create an element or alter the element programmatically. The support for JavaScript technology DOM APIs can differ in various browsers, so you must take care when developing applications.
  • 24.
  • 25. In a word, a program does not wait for response after requesting an asynchronous call whereas synchronous does so. Here is a simple example – function check() { var a=0; a = getStatus(“getstatus.php?id=5”); if(a==1) { alert(“active”); } else { alert(“not active”); } }
  • 26. Here getStatus() function sends a AJAX request to the server with “getstatus.php?id=5” url and the php file decides (from database may be) the status and output/response as 1 or 0. But, this function will not work properly. It will alert “not active” instead of “active”. And yes, that is for the asynchronous request. The reason is – when a = getStatus(“getstatus.php?id=5”); line is being executed program does not wait for the response of setStatus() function. So, value of keep unchanged or set to null. So, how should we work with asynchronous request? Of course, using callback function. Callback function is that function which is triggered when the request completes to get the response (or as defined).
  • 27.