Lecture 13 Introduction to AJAX Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU.

Slides:



Advertisements
Similar presentations
Chapter 6 Server-side Programming: Java Servlets
Advertisements

JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
WEB DESIGN TABLES, PAGE LAYOUT AND FORMS. Page Layout Page Layout is an important part of web design Why do you think your page layout is important?
CIS 4004: Web Based Information Technology Spring 2013
AJAX: Asynchronous JavaScript And XML
Chapter 6 Basic forms 1. Forms and query string 2 form : a group of user input (UI) controls that accepts information from the user and sends the information.
9. AJAX & RIA. 2 Motto: O! call back yesterday, bid time return. — William Shakespeare.
HTML Form Processing Learning Web Design – Chapter 9, pp Squirrel Book – Chapter 11, pp
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,
Python and Web Programming
Comp 519: Web Programming Autumn 2014 Ajax Basic objects necessary Setting up the XMLHttpRequest object Making the call How the server responds Using the.
Computer Science 101 Web Access to Databases Overview of Web Access to Databases.
Chapter 6 DOJO TOOLKITS. Objectives Discuss XML DOM Discuss JSON Discuss Ajax Response in XML, HTML, JSON, and Other Data Type.
Christopher M. Pascucci Basic Structural Concepts of.NET Browser – Server Interaction.
JQuery CS 268. What is jQuery? From their web site:
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
PHP Tutorials 02 Olarik Surinta Management Information System Faculty of Informatics.
Reading Data in Web Pages tMyn1 Reading Data in Web Pages A very common application of PHP is to have an HTML form gather information from a website's.
Ajax (Asynchronous JavaScript and XML). AJAX  Enable asynchronous communication between a web client and a server.  A client is not blocked when an.
PHP and AJAX ISYS 475. AJAX Asynchronous JavaScript and XML: – JavaScript, Document Object Model, Cascade Style Sheet, XML, server-side script such as.Net,
JavaScript & jQuery the missing manual Chapter 11
1 HTML and CGI Scripting CSC8304 – Computing Environments for Bioinformatics - Lecture 10.
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
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.
CNIT 133 Interactive Web Pags – JavaScript and AJAX JavaScript Environment.
PHP meets MySQL.
06/10/2015AJAX 1. 2 Introduction All material from AJAX – what is it? Traditional web pages and operation Examples of AJAX use Creating.
Creating Dynamic Web Pages Using PHP and MySQL CS 320.
Using Client-Side Scripts to Enhance Web Applications 1.
Forms and Server Side Includes. What are Forms? Forms are used to get user input We’ve all used them before. For example, ever had to sign up for courses.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Database Handling, Sessions, and AJAX. Post Back ASP.NET Functionality The IsPostBack method in ASP.NET is similar to the BlackBerry.refresh method –IsPostBack.
Dynamic web content HTTP and HTML: Berners-Lee’s Basics.
Lecture 9: AJAX, Javascript review..  AJAX  Synchronous vs. asynchronous browsing.  Refreshing only “part of a page” from a URL.  Frameworks: Prototype,
AJAX محمد احمدی نیا 2 Of 27 What is AJAX?  AJAX = Asynchronous JavaScript and XML.  AJAX is not a new programming language, but.
Java server pages. A JSP file basically contains HTML, but with embedded JSP tags with snippets of Java code inside them. A JSP file basically contains.
Rails & Ajax Module 5. Introduction to Rails Overview of Rails Rails is Ruby based “A development framework for Web-based applications” Rails uses the.
Introduction to JavaScript CS101 Introduction to Computing.
Asynchronous Javascript And XML AJAX : an introduction UFCEUS-20-2 : Web Programming.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
IS-907 Java EE World Wide Web - Overview. World Wide Web - History Tim Berners-Lee, CERN, 1990 Enable researchers to share information: Remote Access.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
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.
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.
Text INTRODUCTION TO ASP.NET. InterComm Campaign Guidelines CONFIDENTIAL Simply Server side language Simplified page development model Modular, well-factored,
Web Technology (NCS-504) Prepared By Mr. Abhishek Kesharwani Assistant Professor,UCER Naini,Allahabad.
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?
1 CSC160 Chapter 1: Introduction to JavaScript Chapter 2: Placing JavaScript in an HTML File.
JavaScript, Sixth Edition Chapter 11 Updating Web Pages with Ajax.
CITA 330 Section 10 Web Remoting Techniques. Web Remoting Web Remoting is a term used to categorize the technique of using JavaScript to directly make.
Web Programming Java Script-Introduction. What is Javascript? JavaScript is a scripting language using for the Web. JavaScript is a programming language.
AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library.
National College of Science & Information Technology.
Ajax Basic objects necessary Setting up the XMLHttpRequest object
JavaScript and Ajax (Ajax Tutorial)
CSE 154 Lecture 11: AJAx.
Not a Language but a series of techniques
AJAX and REST.
XMLHttp Object.
CSE 154 Lecture 11: AJAx.
CSE 154 Lecture 22: AJAX.
ISC440: Web Programming 2 AJAX
JavaScript & jQuery AJAX.
Software Engineering for Internet Applications
Presentation transcript:

Lecture 13 Introduction to AJAX Presented By Dr. Shazzad Hosain Asst. Prof. EECS, NSU

2 CSE382/ETE334: Internet & Web Technology AJAX: Asynchronous JavaScript and XML Lecture Contents Basic objects necessary Basic objects necessary Setting up the XMLHttpRequest object Setting up the XMLHttpRequest object Making the call Making the call How the server responds How the server responds Using the reply Using the reply XML basics XML basics Example: Live search Example: Live search

3 The usual way we operate in the Web Typical browsing behaviour consists of loading a web page, then selecting some action that we want to do, filling out a form, submitting the information, etc. Typical browsing behaviour consists of loading a web page, then selecting some action that we want to do, filling out a form, submitting the information, etc. We work in this sequential manner, requesting one page at a time, and have to wait for the server to respond, loading a whole new web page before we continue. We work in this sequential manner, requesting one page at a time, and have to wait for the server to respond, loading a whole new web page before we continue. This is also one of the limitations of web pages, where transmitting information between a client and server generally requires a new page to be loaded. This is also one of the limitations of web pages, where transmitting information between a client and server generally requires a new page to be loaded.

4 The usual way we operate in the Web JavaScript is one way to cut down on (some of) the client-server response time, by using it to verify form (or other) information before it’s submitted to a server. JavaScript is one way to cut down on (some of) the client-server response time, by using it to verify form (or other) information before it’s submitted to a server. One of the limitations of JavaScript is (or used to be) that there was no way to communicate directly with a web server. One of the limitations of JavaScript is (or used to be) that there was no way to communicate directly with a web server. Another drawback to this usual sequential access method is that there are many situations where you load a new page that shares lots of the same parts as the old (consider the case where you have a “menu bar” on the top or side of the page that doesn’t change from page to page). Another drawback to this usual sequential access method is that there are many situations where you load a new page that shares lots of the same parts as the old (consider the case where you have a “menu bar” on the top or side of the page that doesn’t change from page to page).

5 Things change… Until recently, we didn’t have any alternative to this load/wait/respond method of web browsing. Until recently, we didn’t have any alternative to this load/wait/respond method of web browsing. Ajax (sometimes written AJAX) is a means of using JavaScript to communicate with a web server without submitting a form or loading a new page. Ajax (sometimes written AJAX) is a means of using JavaScript to communicate with a web server without submitting a form or loading a new page. Ajax makes use of a built-in object, XMLHttpRequest, to perform this function. Ajax makes use of a built-in object, XMLHttpRequest, to perform this function. This object is not yet part of the DOM (Document Object Model) standard, but is supported (in different fashions) by Firefox, Internet Explorer, Safari, Opera, and other popular browsers. This object is not yet part of the DOM (Document Object Model) standard, but is supported (in different fashions) by Firefox, Internet Explorer, Safari, Opera, and other popular browsers. The term “Ajax” was coined in 2005, but the XMLHttpRequest object was first supported by Internet Explorer several years before this. The term “Ajax” was coined in 2005, but the XMLHttpRequest object was first supported by Internet Explorer several years before this.

6Ajax Ajax stands for “Asynchronous JavaScript and XML”. Ajax stands for “Asynchronous JavaScript and XML”. The word “asynchronous” means that the user isn’t left waiting for the server the respond to a request, but can continue using the web page. The word “asynchronous” means that the user isn’t left waiting for the server the respond to a request, but can continue using the web page. The typical method for using Ajax is the following: The typical method for using Ajax is the following: 1) A JavaScript creates an XMLHttpRequest object, initializes it with 1) A JavaScript creates an XMLHttpRequest object, initializes it with relevant information as necessary, and sends it to the server. The script relevant information as necessary, and sends it to the server. The script (or web page) can continue after sending it to the server. (or web page) can continue after sending it to the server. 2) The server responds by sending the contents of a file or the output of a 2) The server responds by sending the contents of a file or the output of a server side program (written, for example, in PHP). server side program (written, for example, in PHP). 3) When the response arrives from the server, a JavaScript function is 3) When the response arrives from the server, a JavaScript function is triggered to act on the data supplied by the server. triggered to act on the data supplied by the server. 4) This JavaScript response function typically refreshes the display using the 4) This JavaScript response function typically refreshes the display using the DOM, avoiding the requirement to reload or refresh the entire page. DOM, avoiding the requirement to reload or refresh the entire page.

7 How Does AJAX Work? Client’s Browser Web Server HTTP JavaScript Module Database or Other Data JSP Page/PHP HTML Page Event handlers, etc. JDBC,ODBC etc.

8 The Back End The part of the Ajax application that resides on the web server is referred to as the “back end”. The part of the Ajax application that resides on the web server is referred to as the “back end”. This back end could be simply a file that the server passes back to the client, which is then displayed for the user. This back end could be simply a file that the server passes back to the client, which is then displayed for the user. Alternatively, the back end could be a program, written in PHP, Perl, Ruby, Python, C, or some other language that performs an operation and sends results back to the client browser. Alternatively, the back end could be a program, written in PHP, Perl, Ruby, Python, C, or some other language that performs an operation and sends results back to the client browser. An XMLHttpRequest object can send information using the GET and POST methods to the server in the same way that an HTML form sends information. An XMLHttpRequest object can send information using the GET and POST methods to the server in the same way that an HTML form sends information. Recall from our previous discussions that the GET request encodes the information inside of the URL, while a POST request sends its data separately (and can contain more information than a GET request can). Recall from our previous discussions that the GET request encodes the information inside of the URL, while a POST request sends its data separately (and can contain more information than a GET request can).

9 Writing an Ajax application We have to write the “front end” of the application in JavaScript to initiate the request. We have to write the “front end” of the application in JavaScript to initiate the request. The back end, as mentioned, processes the request and sends it’s response back to the client. The back end is typically a short program we write for performing some dedicated task. This could be scripted in any language that is capable of sending back communication to the browser, like PHP or Perl. The back end, as mentioned, processes the request and sends it’s response back to the client. The back end is typically a short program we write for performing some dedicated task. This could be scripted in any language that is capable of sending back communication to the browser, like PHP or Perl. We also need to write the JavaScript response function for processing the response and displaying any results (or alterations to the web page). We also need to write the JavaScript response function for processing the response and displaying any results (or alterations to the web page). The “x” in Ajax stands for XML, the extensible markup language. XML looks like HTML, which is no mistake as the latest versions of HTML are built upon XML. The “x” in Ajax stands for XML, the extensible markup language. XML looks like HTML, which is no mistake as the latest versions of HTML are built upon XML. The back end could send data back in XML format and the JavaScript response function can process it using built-in functions for working with XML. The back end could also send plain text, HTML, or even data in the JavaScript format. The back end could send data back in XML format and the JavaScript response function can process it using built-in functions for working with XML. The back end could also send plain text, HTML, or even data in the JavaScript format. We will discuss some of these methods for sending data back to the requesting client and how it can be processed. We will discuss some of these methods for sending data back to the requesting client and how it can be processed.

10 The XMLHttpRequest object The XMLHttpRequest object is the backbone of every Ajax method. Each application requires the creation of one of these objects. So how do we do it? The XMLHttpRequest object is the backbone of every Ajax method. Each application requires the creation of one of these objects. So how do we do it? As with most things in web programming, this depends upon the web browser that the client is using because of the different ways in which the object has been implemented in the browsers. As with most things in web programming, this depends upon the web browser that the client is using because of the different ways in which the object has been implemented in the browsers. Firefox, Safari, Opera, and some other browsers can create one of these objects simply using the “new” keyword. Firefox, Safari, Opera, and some other browsers can create one of these objects simply using the “new” keyword. ajaxRequest = new XMLHttpRequest(); ajaxRequest = new XMLHttpRequest();

11 The XMLHttpRequest object (cont.) Microsoft Internet Explorer implements this object using it’s proprietary ActiveX technology. This requires a different syntax for creating the object (and can also depend upon the particular version of Internet Explorer being used). Microsoft Internet Explorer implements this object using it’s proprietary ActiveX technology. This requires a different syntax for creating the object (and can also depend upon the particular version of Internet Explorer being used). To handle different types of browsers, we use the format: To handle different types of browsers, we use the format: try {... } catch (error) {... } try {... } catch (error) {... } The “try” section attempts to execute some JavaScipt code. If an error occurs, the “catch” section is used to intervene before the error crashes the JavaScript (either to indicate an error has happened, or to attempt something else). The “try” section attempts to execute some JavaScipt code. If an error occurs, the “catch” section is used to intervene before the error crashes the JavaScript (either to indicate an error has happened, or to attempt something else). To create one of these objects we can use a sequence of try... catch blocks, attempting different ways to create an XMLHttpRequest object. To create one of these objects we can use a sequence of try... catch blocks, attempting different ways to create an XMLHttpRequest object.

12 The XMLHttpRequest object (cont.) function getXMLHttpRequest() /* This function attempts to get an Ajax request object by trying a few different methods for different browsers. */ a few different methods for different browsers. */{ var request, err; var request, err; try { try { request = new XMLHttpRequest(); // Firefox, Safari, Opera, etc. request = new XMLHttpRequest(); // Firefox, Safari, Opera, etc. } catch(err) { catch(err) { try { // first attempt for Internet Explorer try { // first attempt for Internet Explorer request = new ActiveXObject("MSXML2.XMLHttp.6.0"); request = new ActiveXObject("MSXML2.XMLHttp.6.0"); } catch (err) { catch (err) { try { // second attempt for Internet Explorer try { // second attempt for Internet Explorer request = new ActiveXObject("MSXML2.XMLHttp.3.0"); request = new ActiveXObject("MSXML2.XMLHttp.3.0"); } catch (err) { catch (err) { request = false; // oops, can’t create one! request = false; // oops, can’t create one! } } } return request; return request;} If this function doesn’t return “false” then we were successful in creating an XMLHttpRequest object. If this function doesn’t return “false” then we were successful in creating an XMLHttpRequest object.

13 The XMLHttpRequest object (cont.) As with any object in JavaScript (and other programming languages), the XMLHttpRequest object contains various properties and methods. As with any object in JavaScript (and other programming languages), the XMLHttpRequest object contains various properties and methods. We list the most important of these properties and methods on the next pages. We list the most important of these properties and methods on the next pages. The main idea is that the properties are set after the object is created to specify information to be sent to the server, as well as how to handle the response received from the server. Some properties will be updated to hold status information about whether the request finished successfully. The main idea is that the properties are set after the object is created to specify information to be sent to the server, as well as how to handle the response received from the server. Some properties will be updated to hold status information about whether the request finished successfully. The methods are used to send the request to the server, and to monitor the progress of the request as it is executed (and to determine if it was completed successfully). The methods are used to send the request to the server, and to monitor the progress of the request as it is executed (and to determine if it was completed successfully).

14 XMLHttpRequest object properties Property Description Property Description_____________________________________________________________________________ readyState An integer from (0 means the call readyState An integer from (0 means the call is uninitialized, 4 means that the call is is uninitialized, 4 means that the call is complete.) complete.) onreadystatechange Determines the function called when the onreadystatechange Determines the function called when the objects readyState changes. objects readyState changes. responseText Data returned from the server as a text responseText Data returned from the server as a text string (read-only). string (read-only). responseXML Data returned from the server as an XML responseXML Data returned from the server as an XML document object (read-only). document object (read-only). status HTTP status code returned by the server status HTTP status code returned by the server statusText HTTP status phrase returned by the server statusText HTTP status phrase returned by the server We use the readyState to determine when the request has been completed, and then check the status to see if it executed without an error. (We’ll see how to do this shortly.) We use the readyState to determine when the request has been completed, and then check the status to see if it executed without an error. (We’ll see how to do this shortly.) var READY_STATE_UNINITIALIZED = 0; var READY_STATE_LOADING = 1; var READY_STATE_LOADED = 2; var READY_STATE_INTERACTIVE = 3; var READY_STATE_COMPLETE = 4;

15 XMLHttpRequest object methods Method Description Method Description open(‘method’, ’URL’, asyn) Specifies the HTTP method to be used (GET open(‘method’, ’URL’, asyn) Specifies the HTTP method to be used (GET or POST as a string, the target URL, and or POST as a string, the target URL, and whether or not the request should be whether or not the request should be handled asynchronously (asyn should be handled asynchronously (asyn should be true or false, if omitted, true is true or false, if omitted, true is assumed). assumed). send(content) Sends the data for a POST request and send(content) Sends the data for a POST request and starts the request, if GET is used you starts the request, if GET is used you should call send(null). should call send(null). setRequestHeader(‘x’,‘y’) Sets a parameter and value pair x=y and setRequestHeader(‘x’,‘y’) Sets a parameter and value pair x=y and assigns it to the header to be sent with assigns it to the header to be sent with the request. the request. getAllResponseHeaders() Returns all headers as a string. getAllResponseHeaders() Returns all headers as a string. getResponseHeader(x) Returns header x as a string. getResponseHeader(x) Returns header x as a string. abort() Stops the current operation. abort() Stops the current operation. The open object method is used to set up the request, and the send method starts the request by sending it to the server (with data for the server if the POST method is used). The open object method is used to set up the request, and the send method starts the request by sending it to the server (with data for the server if the POST method is used).

16 A general skeleton for an Ajax application // ***** include the getXMLHttpRequest function defined before // ***** include the getXMLHttpRequest function defined before var ajaxRequest = getXMLHttpRequest(); if (ajaxRequest) { // if the object was created successfully ajaxRequest.onreadystatechange = ajaxResponse; ajaxRequest.onreadystatechange = ajaxResponse; ajaxRequest.open(“GET”, “search.php?query=Bob”); ajaxRequest.open(“GET”, “search.php?query=Bob”); ajaxRequest.send(null); ajaxRequest.send(null); } function ajaxResponse() //This gets called when the readyState changes. { if (ajaxRequest.readyState != 4) // check to see if we’re done if (ajaxRequest.readyState != 4) // check to see if we’re done { return; } { return; } else { else { if (ajaxRequest.status == 200) // check to see if successful if (ajaxRequest.status == 200) // check to see if successful { // process server data here... } { // process server data here... } else { else { alert(“Request failed: “ + ajaxRequest.statusText); alert(“Request failed: “ + ajaxRequest.statusText); } }}</script>

17 A first example Here’s an example to illustrate the ideas we’ve mentioned (inspired by an example in the book Ajax in 10 Minutes by Phil Ballard). Here’s an example to illustrate the ideas we’ve mentioned (inspired by an example in the book Ajax in 10 Minutes by Phil Ballard). The main idea is that we’re going to get the time on the server and display it to the screen (and provide a button for a user to update this time). The point I want to demonstrate here is how to use Ajax to do this update without updating/refreshing the entire webpage. The main idea is that we’re going to get the time on the server and display it to the screen (and provide a button for a user to update this time). The point I want to demonstrate here is how to use Ajax to do this update without updating/refreshing the entire webpage. We use a (very) small PHP script to get the date from the server, and return it as a string as a response to the request. Here is the script: We use a (very) small PHP script to get the date from the server, and return it as a string as a response to the request. Here is the script: <?php <?php echo date('H:i:s'); echo date('H:i:s'); ?> ?> I saved this as the file “telltime.php”. I saved this as the file “telltime.php”. The HTML file and JavaScript code follows. The HTML file and JavaScript code follows.

18 Ajax Demonstration Ajax Demonstration Getting the server time without refreshing the page Getting the server time without refreshing the page <form> </form> </body></html> The main functionality is handled by the getServerTime() function in setting up and sending the XMLHttpRequest object, and the ajaxResponse() function to display the time. The main functionality is handled by the getServerTime() function in setting up and sending the XMLHttpRequest object, and the ajaxResponse() function to display the time. view the output page view the output page

19 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " " <head> Ajax Demonstration Ajax Demonstration <style> body { background-color: #CCCCCC; background-color: #CCCCCC; text-align: center; text-align: center; }.displaybox { margin: auto; margin: auto; width: 150px; width: 150px; background-color: #FFFFFF; background-color: #FFFFFF; border: 2px solid #000000; border: 2px solid #000000; padding: 10px; padding: 10px; font: 1.5em normal verdana, helvetica, arial, sans-serif; font: 1.5em normal verdana, helvetica, arial, sans-serif; }</style> var ajaxRequest; function getXMLHttpRequest() /* This function attempts to get an Ajax request object by trying a few different methods for different browsers. */ a few different methods for different browsers. */{ // same code as before... // same code as before...}

20 function ajaxResponse() //This gets called when the readyState changes. { if (ajaxRequest.readyState != 4) // check to see if we're done if (ajaxRequest.readyState != 4) // check to see if we're done { return; } { return; } else { else { if (ajaxRequest.status == 200) // check to see if successful if (ajaxRequest.status == 200) // check to see if successful { document.getElementById("showtime").innerHTML = document.getElementById("showtime").innerHTML = ajaxRequest.responseText; } ajaxRequest.responseText; } else { else { alert("Request failed: " + ajaxRequest.statusText); alert("Request failed: " + ajaxRequest.statusText); } }} function getServerTime() // The main JavaScript for calling the update. { ajaxRequest = getXMLHttpRequest(); ajaxRequest = getXMLHttpRequest(); if (!ajaxRequest) { if (!ajaxRequest) { document.getElementById("showtime").innerHTML = "Request error!"; document.getElementById("showtime").innerHTML = "Request error!"; return; } return; } var myURL = "telltime.php"; var myURL = "telltime.php"; var myRand = parseInt(Math.random()* ); var myRand = parseInt(Math.random()* ); myURL = myURL + "?rand=" + myRand; myURL = myURL + "?rand=" + myRand; ajaxRequest.onreadystatechange = ajaxResponse; ajaxRequest.onreadystatechange = ajaxResponse; ajaxRequest.open("GET", myURL); ajaxRequest.open("GET", myURL); ajaxRequest.send(null); ajaxRequest.send(null);}</script></head>

21 What’s this business with the random numbers? Web browsers use caches to store copies of the web page. Depending upon how they are set up, a browser could use data from it’s cache instead of making a request to the web server. Web browsers use caches to store copies of the web page. Depending upon how they are set up, a browser could use data from it’s cache instead of making a request to the web server. The whole point of Ajax is to make server requests and not to read data from the cache. To avoid this potential problem, we can add a parameter with a random string to the URL so that the browser won’t be reading data from its cache to satisfy the request (as then it looks like a different request than previous ones). The whole point of Ajax is to make server requests and not to read data from the cache. To avoid this potential problem, we can add a parameter with a random string to the URL so that the browser won’t be reading data from its cache to satisfy the request (as then it looks like a different request than previous ones). This is only necessary if the request method is GET, as POST requests don’t use the cache. (This also seems to be more of an issue with Microsoft Internet Explorer than with other browsers.) This is only necessary if the request method is GET, as POST requests don’t use the cache. (This also seems to be more of an issue with Microsoft Internet Explorer than with other browsers.)

22 Sending text back the server The response stored in XMLHttpRequest.responseText from the server can be any text that JavaScript is capable of processing as a string. The response stored in XMLHttpRequest.responseText from the server can be any text that JavaScript is capable of processing as a string. Thus, you can send back a simple text string as the first example did, or you could send a string with HTML tags embedded in it. You can process the string using JavaScript functions (to split it into substrings, add/delete parts of it, etc.). Thus, you can send back a simple text string as the first example did, or you could send a string with HTML tags embedded in it. You can process the string using JavaScript functions (to split it into substrings, add/delete parts of it, etc.). You could even send back a string that has JavaScript code it in and execute it using the JavaScript eval() method. You could even send back a string that has JavaScript code it in and execute it using the JavaScript eval() method. Recall, however, that the responseText property is a read-only variable, so if you’re going to alter it you must first copy it to another variable. Recall, however, that the responseText property is a read-only variable, so if you’re going to alter it you must first copy it to another variable. (Change the PHP script to insert HTML tags.) (Change the PHP script to insert HTML tags.) (As next page, change the PHP script.) (As next page, change the PHP script.) Example with HTML tag Example using a table

23 The other PHP scripts for the time examples Here’s the script with a simple HTML tag in it. Here’s the script with a simple HTML tag in it. <?php <?php echo ' '. date('H:i:s'). " "; echo ' '. date('H:i:s'). " "; ?> ?> The output with a table. The output with a table.<?php $tr = ' '; $td = ' '; $table = ' '; $table.= $tr. $td. date('j M Y'). ' '; $table.= $tr. $td. date('H:i:s'). ' '; $table.= ' '; echo $table; ?>

24 XML: a (very) brief intro XML, the eXtensible Markup Language, is used in many ways, the most relevant to us being the transfer of structured information. XML, the eXtensible Markup Language, is used in many ways, the most relevant to us being the transfer of structured information. XML and HTML look similar in many ways and this is because both are based on SGML, the Standard Generalized Markup Language established by the International Organization for Standards (ISO). XML and HTML look similar in many ways and this is because both are based on SGML, the Standard Generalized Markup Language established by the International Organization for Standards (ISO). Like HTML, XML uses tags to denote information but is not limited to the types of tags that occur in HTML. Tags can be essentially anything a user likes and are used to define the type of data present in the document. Like HTML, XML uses tags to denote information but is not limited to the types of tags that occur in HTML. Tags can be essentially anything a user likes and are used to define the type of data present in the document.

25 XML: a (very) brief intro (cont.) Here’s an example: Here’s an example:<library> Programming PHP Programming PHP Rasmus Lerdorf Rasmus Lerdorf Kevin Tatroe Kevin Tatroe Peter MacIntyre Peter MacIntyre Introduction to PHP Introduction to PHP Language Basics Language Basics </library>

26 Accessing an XML document in JavaScript To use an XML document in JavaScript, you must create an object to hold it. This can be done in the following fashion: To use an XML document in JavaScript, you must create an object to hold it. This can be done in the following fashion: Non-Microsoft browsers: Non-Microsoft browsers: var myXMLDoc = document.implementation.createDocument(“”,””,null); var myXMLDoc = document.implementation.createDocument(“”,””,null); myXMLDoc.load(“mydoc.xml”); myXMLDoc.load(“mydoc.xml”); // other code here // other code here Internet Explorer: Internet Explorer: var myXMLDoc = new ActiveXObject(“Microsoft.XMLDOM”); var myXMLDoc = new ActiveXObject(“Microsoft.XMLDOM”); myXMLDoc.async=“false”; myXMLDoc.async=“false”; myXMLDoc.load(“mydoc.xml”); myXMLDoc.load(“mydoc.xml”); // other code here // other code here Once we’ve created the object holding the XML document, we can then use JavaScript methods to examine it, extract data from it, etc. Once we’ve created the object holding the XML document, we can then use JavaScript methods to examine it, extract data from it, etc.

27 The “time” example using XML The first change is to make a new PHP script that returns an XML document to the browser. The first change is to make a new PHP script that returns an XML document to the browser. <?php <?php header('Content-Type: text/xml'); header('Content-Type: text/xml'); echo " \n”; echo " \n”; echo “ ". date('H:i:s'). " "; echo “ ". date('H:i:s'). " "; ?> ?> After that change (and inserting the new script name into the HTML code), we need to alter the ajaxResponse function to parse the XML document. That new JavaScript function is given on the next page. After that change (and inserting the new script name into the HTML code), we need to alter the ajaxResponse function to parse the XML document. That new JavaScript function is given on the next page. Note that we need not explicitly create an object to hold the XML document, but that responseXML (as a property of XMLHttpRequest) is already such an object. Note that we need not explicitly create an object to hold the XML document, but that responseXML (as a property of XMLHttpRequest) is already such an object.

28 The new Ajax response function function ajaxResponse() //This gets called when the readyState changes. { if (ajaxRequest.readyState != 4) // check to see if we're done if (ajaxRequest.readyState != 4) // check to see if we're done { return; } { return; } else { else { if (ajaxRequest.status == 200) // check to see if successful if (ajaxRequest.status == 200) // check to see if successful { var timeValue = { var timeValue = ajaxRequest.responseXML.getElementsByTagName("timenow")[0]; ajaxRequest.responseXML.getElementsByTagName("timenow")[0]; document.getElementById("showtime").innerHTML = document.getElementById("showtime").innerHTML = timeValue.childNodes[0].nodeValue; } timeValue.childNodes[0].nodeValue; } else { else { alert("Request failed: " + ajaxRequest.statusText); alert("Request failed: " + ajaxRequest.statusText); } }} This new response function uses a JavaScript method to access the XML DOM and retrieve the time string before inserting it into the output display box. This new response function uses a JavaScript method to access the XML DOM and retrieve the time string before inserting it into the output display box. view the output page view the output page

29 Ajax Demonstration Ajax Demonstration Getting the server time without refreshing the page Getting the server time without refreshing the page <form> </form> </body></html> The main functionality is handled by the getServerTime() function in setting up and sending the XMLHttpRequest object, and the ajaxResponse() function to display the time. The main functionality is handled by the getServerTime() function in setting up and sending the XMLHttpRequest object, and the ajaxResponse() function to display the time. view the output page view the output page

30 Web Application Architecture with AJAX JSON: JavaScript Object Notation

31 A Second example (live search) We’ll build a “live search” function. When you typically use a form, you must submit the data to the server and wait for it to return the results. Here we want to consider a case where you get (partial) results as you enter data into the input field, and that these results are updated (almost) instantly. We’ll build a “live search” function. When you typically use a form, you must submit the data to the server and wait for it to return the results. Here we want to consider a case where you get (partial) results as you enter data into the input field, and that these results are updated (almost) instantly. Note: This example has been adapted from the book JavaScript in 24 Hours by Michael Moncur. Note: This example has been adapted from the book JavaScript in 24 Hours by Michael Moncur. We use PHP again for the backend. First consider the case where the possible results are a list of names, stored in a PHP array. As you type data into the input field, it’s matched against this list of names, and the (partial) matches are returned and displayed on screen. We use PHP again for the backend. First consider the case where the possible results are a list of names, stored in a PHP array. As you type data into the input field, it’s matched against this list of names, and the (partial) matches are returned and displayed on screen. Later, we will see the same type of application, but using PHP to search through the names stored in a database. Later, we will see the same type of application, but using PHP to search through the names stored in a database.

32 The HTML layout (no JavaScript yet) <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" " " <head> Ajax Demonstration Ajax Demonstration <style></style><script> // The JavaScript front end will be in here. // The JavaScript front end will be in here.</script></head><body> Ajax Demonstration of Live Search Ajax Demonstration of Live Search <p> Search for: Search for: </p> Results will be displayed here. Results will be displayed here. </ul></div> // This sets up the event handler to start the // This sets up the event handler to start the // search function. // search function. // var obj=document.getElementById("searchstring"); // obj.onkeydown = startSearch; </script></body></html> view the output page view the output page

33 The PHP backend search.php <?php header("Content-Type: text/xml"); $people = array( "Abraham Lincoln", "Martin Luther King", "Jimi Hendrix", "John Wayne", "John Carpenter", "Elizabeth Shue", "Benny Hill", "Lou Costello", "Bud Abbott", "Albert Einstein", "Rich Hall", "Lou Costello", "Bud Abbott", "Albert Einstein", "Rich Hall", "Anthony Soprano", "Michelle Rodriguez", "Carmen Miranda", "Anthony Soprano", "Michelle Rodriguez", "Carmen Miranda", "Sandra Bullock", "Moe Howard", "Ulysses S. Grant", "Stephen Fry", "Sandra Bullock", "Moe Howard", "Ulysses S. Grant", "Stephen Fry", "Kurt Vonnegut", "Yosemite Sam", "Ed Norton", "George Armstrong Custer", "Alice Kramden", "Evangeline Lilly", "Harlan Ellison"); "Kurt Vonnegut", "Yosemite Sam", "Ed Norton", "George Armstrong Custer", "Alice Kramden", "Evangeline Lilly", "Harlan Ellison"); if(!$query) $query = $_GET['query']; echo " \n"; while (list($k,$v) = each ($people)) { if (stristr ($v, $query)) if (stristr ($v, $query)) echo " $v \n"; echo " $v \n"; } echo ' '; ?> This PHP script takes the query that will be passed to it, then searches for (case insensitive) matches to the names in the array. This PHP script takes the query that will be passed to it, then searches for (case insensitive) matches to the names in the array. It passes an XML document back to the calling function consisting of the names that it finds. It passes an XML document back to the calling function consisting of the names that it finds.

34 The JavaScript functions We obviously need the function for creating a new XMLHttpRequest object, which we will store in a global variable called “ajaxRequest”. We obviously need the function for creating a new XMLHttpRequest object, which we will store in a global variable called “ajaxRequest”. The search will be handled by setting up a Timeout event, based on entering text in the input field (using the “onkeydown” attribute). The search will be handled by setting up a Timeout event, based on entering text in the input field (using the “onkeydown” attribute). var t; // public variable for the timeout var t; // public variable for the timeout function startSearch() function startSearch() { if (t) window.clearTimeout(t); if (t) window.clearTimeout(t); t = window.setTimeout("liveSearch()",200); t = window.setTimeout("liveSearch()",200); } The “liveSearch” function is the main calling routine, where we set up the XMLHttpRequest object, and make the call to the PHP script. The “liveSearch” function is the main calling routine, where we set up the XMLHttpRequest object, and make the call to the PHP script.

35 The JavaScript functions (cont.) Recall that we’re making ajaxRequest a global variable in the script, so that as in the other example we can access it’s properties in the callback function. Recall that we’re making ajaxRequest a global variable in the script, so that as in the other example we can access it’s properties in the callback function. function liveSearch() { ajaxRequest = getXMLHttpRequest(); ajaxRequest = getXMLHttpRequest(); if (!ajaxRequest) alert("Request error!"); if (!ajaxRequest) alert("Request error!"); var myURL = "search.php"; var myURL = "search.php"; var query = document.getElementById("searchstring").value; var query = document.getElementById("searchstring").value; myURL = myURL + "?query=" + query; myURL = myURL + "?query=" + query; ajaxRequest.onreadystatechange = ajaxResponse; ajaxRequest.onreadystatechange = ajaxResponse; ajaxRequest.open("GET", myURL); ajaxRequest.open("GET", myURL); ajaxRequest.send(null); ajaxRequest.send(null);} function ajaxResponse() //This gets called when the readyState changes. { if (ajaxRequest.readyState != 4) // check to see if we're done if (ajaxRequest.readyState != 4) // check to see if we're done { return; } { return; } else { else { if (ajaxRequest.status == 200) // check to see if successful if (ajaxRequest.status == 200) // check to see if successful { displaySearchResults(); } { displaySearchResults(); } else { else { alert("Request failed: " + ajaxRequest.statusText); alert("Request failed: " + ajaxRequest.statusText); } }}

36 The JavaScript functions (cont.) function displaySearchResults() // This function will display the search results, and is the // callback function for the Ajax request. { var i, n, li, t; var ul = document.getElementById("list"); var ul = document.getElementById("list"); var div = document.getElementById("results"); var div = document.getElementById("results"); div.removeChild(ul); // delete the old search results div.removeChild(ul); // delete the old search results ul = document.createElement("UL"); // create a new list container ul = document.createElement("UL"); // create a new list container ul.id="list"; ul.id="list"; // get the results from the search request object // get the results from the search request object var names=ajaxRequest.responseXML.getElementsByTagName("name"); var names=ajaxRequest.responseXML.getElementsByTagName("name"); for (i = 0; i < names.length; i++) for (i = 0; i < names.length; i++) { li = document.createElement("LI"); // create a new list element li = document.createElement("LI"); // create a new list element n = names[i].firstChild.nodeValue; n = names[i].firstChild.nodeValue;li.appendChild(document.createTextNode(n)); ul.appendChild(li); ul.appendChild(li); } if (names.length == 0) { // if no results are found, say so if (names.length == 0) { // if no results are found, say so li = document.createElement("LI"); li = document.createElement("LI"); li.appendChild(document.createTextNode("No results.")); li.appendChild(document.createTextNode("No results.")); ul.appendChild(li); ul.appendChild(li); } div.appendChild(ul); // display the new list div.appendChild(ul); // display the new list}

37 The Finished product We add all of the functions (and the two global variables) to the header script section, uncomment the two lines in the other script section and we’re good to go! We add all of the functions (and the two global variables) to the header script section, uncomment the two lines in the other script section and we’re good to go! The fact that the names are in a PHP script allows us to easily add more or delete some of them. If desired, you could have the “search array” in a separate PHP file and include it in the search routine script, allowing you to reuse the same code with many different lists. The fact that the names are in a PHP script allows us to easily add more or delete some of them. If desired, you could have the “search array” in a separate PHP file and include it in the search routine script, allowing you to reuse the same code with many different lists. view the output page view the output page

38 Using a database for the live search Instead of storing the names in an array, we could alter the PHP script to search through a mySQL database for matches. Instead of storing the names in an array, we could alter the PHP script to search through a mySQL database for matches. The JavaScript need not be changed (except for the name of the script to call). The JavaScript need not be changed (except for the name of the script to call). As before, the PHP script will return the names as an XML document, using methods for a case-insensitive search on the query string. As before, the PHP script will return the names as an XML document, using methods for a case-insensitive search on the query string. A new PHP script is shown on the next page. A new PHP script is shown on the next page. Important!!! Remember that since you’re now using PHP with mySQL, you need to access the main webpage via the CGI server. Important!!! Remember that since you’re now using PHP with mySQL, you need to access the main webpage via the CGI server.

39<?php header("Content-Type: text/xml"); Search.php echo " \n"; if(!$query) $query = strtoupper($_GET['query']); if($query != "") { include_once('db_access.php'); include_once('db_access.php'); $connection = mysql_connect($db_host, $db_username, $db_password); $connection = mysql_connect($db_host, $db_username, $db_password); if(!$connection) if(!$connection) { exit("Could not connect to the database: ". htmlspecialchars(mysql_error)); exit("Could not connect to the database: ". htmlspecialchars(mysql_error)); } mysql_select_db($db_database); mysql_select_db($db_database); $select = "SELECT "; $select = "SELECT "; $column = "name "; $column = "name "; $from = "FROM "; $from = "FROM "; $tables = "people "; $tables = "people "; $where = "WHERE "; $where = "WHERE "; $condition = "upper(name) LIKE '%$query%'"; $condition = "upper(name) LIKE '%$query%'"; $SQL_query = htmlentities($select. $column. $from. $tables. $where. $condition); $SQL_query = htmlentities($select. $column. $from. $tables. $where. $condition); $result = mysql_query($SQL_query); $result = mysql_query($SQL_query); while ($row = mysql_fetch_row($result)) while ($row = mysql_fetch_row($result)) { echo " ". $row[0]. " \n"; echo " ". $row[0]. " \n"; } mysql_close($connection); mysql_close($connection); } echo " "; ?> view the output page view the output page

40 Some cautions As with any JavaScript element, you can’t (or shouldn’t) rely upon a user’s browser being able to execute JavaScript (some people turn it off on their browsers). (Of course, there are WebPages that ignore this caution.) As with any JavaScript element, you can’t (or shouldn’t) rely upon a user’s browser being able to execute JavaScript (some people turn it off on their browsers). (Of course, there are WebPages that ignore this caution.) Debug carefully and on many different browsers. Ajax uses features that might not be present in all browsers or they may not operate in the same fashion. Debug carefully and on many different browsers. Ajax uses features that might not be present in all browsers or they may not operate in the same fashion. If you can, indicate to the user that “something is happening” or that something has changed on the page, otherwise they may not notice it. If you can, indicate to the user that “something is happening” or that something has changed on the page, otherwise they may not notice it. Ajax can possibly introduce strange behaviour, like the “Back” button on the browser doesn’t act like it did before (as with any dynamic website), or that if you use some “hidden” elements in your page (generated by Ajax), then they will likely not show up in a form that search engines will recognize. Ajax can possibly introduce strange behaviour, like the “Back” button on the browser doesn’t act like it did before (as with any dynamic website), or that if you use some “hidden” elements in your page (generated by Ajax), then they will likely not show up in a form that search engines will recognize. For the sake of us all (who will be looking at your pages), don’t let “flashy behaviour” be a substitute for actual content, or a well designed layout of your web pages. For the sake of us all (who will be looking at your pages), don’t let “flashy behaviour” be a substitute for actual content, or a well designed layout of your web pages.