SlideShare ist ein Scribd-Unternehmen logo
1 von 27
-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).
 

Weitere ähnliche Inhalte

Was ist angesagt?

&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
 

Was ist angesagt? (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
 

Andere mochten auch

Linkedin pro docs/ how to VII
Linkedin pro docs/ how to VIILinkedin pro docs/ how to VII
Linkedin pro docs/ how to VIIleeramirez
 
Linkedin pro docs/ how to VI
Linkedin pro docs/ how to VILinkedin pro docs/ how to VI
Linkedin pro docs/ how to VIleeramirez
 
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...Luis Felipe Fajardo
 
500mW, 1W RF Data Transmitter, 433MHz RF Module
500mW, 1W RF Data Transmitter, 433MHz RF Module500mW, 1W RF Data Transmitter, 433MHz RF Module
500mW, 1W RF Data Transmitter, 433MHz RF ModuleSunny Zhou
 
Combinational circuits II outputs
Combinational circuits II outputsCombinational circuits II outputs
Combinational circuits II outputsGouthaman V
 
Scholastic averages sheet-2
Scholastic averages sheet-2Scholastic averages sheet-2
Scholastic averages sheet-2Gouthaman V
 
Judo sponsorship 2012
Judo sponsorship 2012Judo sponsorship 2012
Judo sponsorship 2012GM Sponsoring
 
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...sultans570
 
Feasibility Studies: 2-EH Manufacturing
Feasibility Studies: 2-EH ManufacturingFeasibility Studies: 2-EH Manufacturing
Feasibility Studies: 2-EH ManufacturingIntratec Solutions
 
Comprendre, developper et analyser son influence sur les reseaux sociaux
Comprendre, developper et analyser son influence sur les reseaux sociauxComprendre, developper et analyser son influence sur les reseaux sociaux
Comprendre, developper et analyser son influence sur les reseaux sociauxLaurie Martin
 
Economics of Citric Acid Production Processes
Economics of Citric Acid Production ProcessesEconomics of Citric Acid Production Processes
Economics of Citric Acid Production ProcessesIntratec Solutions
 
Feasibility Studies: Hexenes Manufacturing
Feasibility Studies: Hexenes ManufacturingFeasibility Studies: Hexenes Manufacturing
Feasibility Studies: Hexenes ManufacturingIntratec Solutions
 
Economic Analysis: Styrene Production Processes
Economic Analysis: Styrene Production ProcessesEconomic Analysis: Styrene Production Processes
Economic Analysis: Styrene Production ProcessesIntratec Solutions
 
Phonegap
PhonegapPhonegap
PhonegapVISEO
 
Média sociaux: evolution ou révolution (Belfius 17/05/2014)
Média sociaux: evolution ou révolution (Belfius 17/05/2014)Média sociaux: evolution ou révolution (Belfius 17/05/2014)
Média sociaux: evolution ou révolution (Belfius 17/05/2014)Talking Heads
 
Health Rights & the PRIDE Project in Pakistan
Health Rights & the PRIDE Project in PakistanHealth Rights & the PRIDE Project in Pakistan
Health Rights & the PRIDE Project in PakistanSheldon Allen
 
Exp Social Marketing Foundation, Ghana
Exp Social Marketing Foundation, GhanaExp Social Marketing Foundation, Ghana
Exp Social Marketing Foundation, GhanaSheldon Allen
 

Andere mochten auch (19)

Linkedin pro docs/ how to VII
Linkedin pro docs/ how to VIILinkedin pro docs/ how to VII
Linkedin pro docs/ how to VII
 
Software librea ibarrekolanda
Software librea ibarrekolandaSoftware librea ibarrekolanda
Software librea ibarrekolanda
 
Linkedin pro docs/ how to VI
Linkedin pro docs/ how to VILinkedin pro docs/ how to VI
Linkedin pro docs/ how to VI
 
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...
Descomposicióny dinámica de nutrientes de la hojarasca y raícesde los pastos ...
 
500mW, 1W RF Data Transmitter, 433MHz RF Module
500mW, 1W RF Data Transmitter, 433MHz RF Module500mW, 1W RF Data Transmitter, 433MHz RF Module
500mW, 1W RF Data Transmitter, 433MHz RF Module
 
Combinational circuits II outputs
Combinational circuits II outputsCombinational circuits II outputs
Combinational circuits II outputs
 
Scholastic averages sheet-2
Scholastic averages sheet-2Scholastic averages sheet-2
Scholastic averages sheet-2
 
CSS
CSSCSS
CSS
 
Judo sponsorship 2012
Judo sponsorship 2012Judo sponsorship 2012
Judo sponsorship 2012
 
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...
Travelling the path of love: Sayings of the Sufi (Saint) Masters-Llewellyn Va...
 
Feasibility Studies: 2-EH Manufacturing
Feasibility Studies: 2-EH ManufacturingFeasibility Studies: 2-EH Manufacturing
Feasibility Studies: 2-EH Manufacturing
 
Comprendre, developper et analyser son influence sur les reseaux sociaux
Comprendre, developper et analyser son influence sur les reseaux sociauxComprendre, developper et analyser son influence sur les reseaux sociaux
Comprendre, developper et analyser son influence sur les reseaux sociaux
 
Economics of Citric Acid Production Processes
Economics of Citric Acid Production ProcessesEconomics of Citric Acid Production Processes
Economics of Citric Acid Production Processes
 
Feasibility Studies: Hexenes Manufacturing
Feasibility Studies: Hexenes ManufacturingFeasibility Studies: Hexenes Manufacturing
Feasibility Studies: Hexenes Manufacturing
 
Economic Analysis: Styrene Production Processes
Economic Analysis: Styrene Production ProcessesEconomic Analysis: Styrene Production Processes
Economic Analysis: Styrene Production Processes
 
Phonegap
PhonegapPhonegap
Phonegap
 
Média sociaux: evolution ou révolution (Belfius 17/05/2014)
Média sociaux: evolution ou révolution (Belfius 17/05/2014)Média sociaux: evolution ou révolution (Belfius 17/05/2014)
Média sociaux: evolution ou révolution (Belfius 17/05/2014)
 
Health Rights & the PRIDE Project in Pakistan
Health Rights & the PRIDE Project in PakistanHealth Rights & the PRIDE Project in Pakistan
Health Rights & the PRIDE Project in Pakistan
 
Exp Social Marketing Foundation, Ghana
Exp Social Marketing Foundation, GhanaExp Social Marketing Foundation, Ghana
Exp Social Marketing Foundation, Ghana
 

Ähnlich wie AJAX

Ähnlich wie 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
 

Mehr von Gouthaman V

Professional Ethics Assignment II
Professional Ethics Assignment IIProfessional Ethics Assignment II
Professional Ethics Assignment IIGouthaman 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
 
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
 
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
 
VI Semester Examination Time Table
VI Semester Examination Time TableVI Semester Examination Time Table
VI Semester Examination Time TableGouthaman 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
 
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
 
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
 

Mehr von 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
 
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
 
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)
 
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
 
VI Semester Examination Time Table
VI Semester Examination Time TableVI Semester Examination Time Table
VI Semester Examination Time Table
 
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
 
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
 
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
 

Kürzlich hochgeladen

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxVishalSingh1417
 
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...christianmathematics
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
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.pptxnegromaestrong
 
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 Delhikauryashika82
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterMateoGardella
 
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 17Celine George
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingTeacherCyreneCayanan
 

Kürzlich hochgeladen (20)

Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
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
 
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...
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
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
 
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
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Gardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch LetterGardella_PRCampaignConclusion Pitch Letter
Gardella_PRCampaignConclusion Pitch Letter
 
Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024Mehran University Newsletter Vol-X, Issue-I, 2024
Mehran University Newsletter Vol-X, Issue-I, 2024
 
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
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
fourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writingfourth grading exam for kindergarten in writing
fourth grading exam for kindergarten in writing
 

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.