-By V.Gouthaman. INTRODUCTION Ajax (shorthand for asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side.

Slides:



Advertisements
Similar presentations
JavaScript and AJAX Jonathan Foss University of Warwick
Advertisements

AJAX Compiled from “AJAX Programming” [Sang Shin]
6/3/2015eBiquity1 Tutorial on AJAX Anubhav Kale (akale1 AT cs DOT umbc DOT edu)
AJAX Presented by: Dickson Fu Dimas Ariawan Niels Andreassen Ryan Dial Jordan Nielson CMPUT 410 University of Alberta 2006.
19-Jun-15 Ajax. The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better, faster,
Dynamic Web Pages Bert Wachsmuth. Review  Internet, IP addresses, ports, client-server, http, smtp  HTML, XHTML, XML  Style Sheets, external, internal,
1 JavaScript & AJAX CS , Spring JavaScript.
Using AJAX Galip Aydin, Ahmet Sayar, and Marlon Pierce Community Grids Lab Indiana University.
Chapter 6 DOJO TOOLKITS. Objectives Discuss XML DOM Discuss JSON Discuss Ajax Response in XML, HTML, JSON, and Other Data Type.
JQuery CS 268. What is jQuery? From their web site:
Ajax (Asynchronous JavaScript and XML). AJAX  Enable asynchronous communication between a web client and a server.  A client is not blocked when an.
JavaScript & jQuery the missing manual Chapter 11
Chapter 6 JavaScript and AJAX. Objectives Explain the purpose and history of JavaScript Describe JavaScript features Explain the event-driven nature of.
May 16 – 18, 2007 Copyright 2007, Data Access Worldwide May 16 – 18, 2007 Copyright 2007, Data Access Worldwide Build Great Web Application 'Fast and Easy'
Chapter 6: Forms JavaScript - Introductory. Previewing the Product Registration Form.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
Lecture 12 – AJAX SFDV3011 – Advanced Web Development Reference: 1.
Server-side Scripting Powering the webs favourite services.
JavaScript, Fourth Edition Chapter 12 Updating Web Pages with AJAX.
AJAX and Java ISYS 350. AJAX Asynchronous JavaScript and XML: – Related technologies: JavaScript, Document Object Model, XML, server-side script such.
XP New Perspectives on XML, 2 nd Edition Tutorial 10 1 WORKING WITH THE DOCUMENT OBJECT MODEL TUTORIAL 10.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
Writing various AJAX forms in Drupal 7 1. Overview of Form API 2. Ctools 2.1 Ctools features 3. Ajax 3.1 Ajax Forms in Drupal 4. Putting it all together.
JavaScript is a client-side scripting language. Programs run in the web browser on the client's computer. (PHP, in contrast, is a server-side scripting.
Review IDIA 619 Spring 2013 Bridget M. Blodgett. HTML A basic HTML document looks like this: Sample page Sample page This is a simple sample. HTML user.
SEG3210 DHTML Tutorial. DHTML DHTML is a combination of technologies used to create dynamic and interactive Web sites. –HTML - For creating text and image.
JSP Architecture Outline  Model 1 Architecture  Model 2 Architecture.
06/10/2015AJAX 1. 2 Introduction All material from AJAX – what is it? Traditional web pages and operation Examples of AJAX use Creating.
Client side web programming Introduction Jaana Holvikivi, DSc. School of ICT.
Web Server Programming 1. Nuts and Bolts. Premises of Course Provides general introduction, no in-depth training Assumes some HTML knowledge Assumes some.
INTRODUCTION TO JAVASCRIPT AND DOM Internet Engineering Spring 2012.
Extending HTML CPSC 120 Principles of Computer Science April 9, 2012.
Lecture 9: AJAX, Javascript review..  AJAX  Synchronous vs. asynchronous browsing.  Refreshing only “part of a page” from a URL.  Frameworks: Prototype,
AJAX Compiled from “AJAX Programming” [Sang Shin] (Asynchronous JavaScript and XML)
Asynchronous Javascript And XML AJAX : an introduction UFCEUS-20-2 : Web Programming.
the acronym for Asynchronous JavaScript and XML.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
 Previous lessons have focused on client-side scripts  Programs embedded in the page’s HTML code  Can also execute scripts on the server  Server-side.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
Web Technologies Lecture 7 Synchronous vs. asynchronous.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
JQuery and AJAX WEB Technologies : PHP Programming Language.
SE-2840 Dr. Mark L. Hornick 1 Introduction to Ajax Asynchronous Javascript And XML.
AJAX. Overview of Ajax Ajax is not an API or a programming language Ajax aims to provide more responsive web applications In normal request/response HTTP.
CHAPTER 8 AJAX & JSON WHAT IS AJAX? Ajax lets you…
AJAX and REST. Slide 2 What is AJAX? It’s an acronym for Asynchronous JavaScript and XML Although requests need not be asynchronous It’s not really a.
AJAX – Asynchronous JavaScript And XML By Kranthi Kiran Nuthi CIS 764 Kansas State University.
INNOV-2: Build a Better Web Interface Using AJAX Chris Morgan Pandora Software Systems
Web Technology (NCS-504) Prepared By Mr. Abhishek Kesharwani Assistant Professor,UCER Naini,Allahabad.
 AJAX technology  Rich User Experience  Characteristics  Real live examples  JavaScript and AJAX  Web application workflow model – synchronous vs.
Introduction to JavaScript MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/2/2016.
AJAX CS456 Fall Examples Where is AJAX used? Why do we care?
Introduction to AJAX MIS 3502, Spring 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 2/4/2016.
JavaScript, Sixth Edition Chapter 11 Updating Web Pages with Ajax.
A New Way To Web Applications Development Tin Htut Htut Naing Oo Myanmar Information Technology.
JavaScript and Ajax Week 10 Web site:
AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library.
AJAX Rohan B Thimmappa. What Is AJAX? AJAX stands for Asynchronous JavaScript and XML. AJAX stands for Asynchronous JavaScript and XML. A remote scripting.
Introduction to JavaScript MIS 3502, Fall 2016 Jeremy Shafer Department of MIS Fox School of Business Temple University 9/29/2016.
JavaScript and Ajax (Ajax Tutorial)
Not a Language but a series of techniques
AJAX and REST.
AJAX – Asynchronous JavaScript and XML
AJAX.
Introduction to AJAX MIS 3502 Jeremy Shafer Department of MIS
Introduction to AJAX MIS 3502 Jeremy Shafer Department of MIS
AJAX Robin Burke ECT 360.
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Presentation transcript:

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

Now let's look at each step of the Ajax interaction in more detail. 1.A client event occurs. JavaScript technology functions are called as the result of an event. In this case, the function validate() may be mapped to a onkeyup event on a link or form component.

<input type="text" size="20" id="userid" name="id" onkeyup="validate();"> 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("userid"); var url = "validate?id=" + encodeURIComponent(idField.value); if (typeof XMLHttpRequest != "undefined") { req = new XMLHttpRequest(); } else if (window.ActiveXObject) { req = new ActiveXObject("Microsoft.XMLHTTP"); } req.open("GET", 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("Content-Type", "application/x- www-form-urlencoded"); req.send("id=" + 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 "validate" 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("greg","account data"); users.put("duke","account data"); }

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String targetId = request.getParameter("id"); if ((targetId != null) && !users.containsKey(targetId.trim())) { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" valid "); } else { response.setContentType("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" invalid "); } 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("text/xml"); response.setHeader("Cache-Control", "no-cache"); response.getWriter().write(" invalid ")

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.

valid 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("message")[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("userIdMessage"), where "userIdMessage" 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.

... function setMessage(message) { var mdiv = document.getElementById("userIdMessage"); if (message == "invalid") { mdiv.innerHTML = " Invalid User Id "; } else { mdiv.innerHTML = " Valid User Id "; }

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 or, 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.

... function setMessage(message) { var userMessageElement = document.getElementById("userIdMessage"); var messageText; if (message == "invalid") { userMessageElement.style.color = "red"; messageText = "Invalid User Id"; } else { userMessageElement.style.color = "green"; messageText = "Valid User Id"; } 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); } 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? The most common answer is – “AJAX does not refresh or reload the whole page”. But, the more perfect answer is – “AJAX is an asynchronous technology where others request are synchronous.”

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