Ajax - Part II Communicating with the Server. Learning Objectives By the end of this lecture, you should be able to: – Describe the overview of steps.

Slides:



Advertisements
Similar presentations
JQuery MessageBoard. Lets use jQuery and AJAX in combination with a database to update and retrieve information without refreshing the page. Here we will.
Advertisements

CIS 4004: Web Based Information Technology Spring 2013
JQUERY/AJAX ALIREZA KHATAMIAN DELARAM YAZDANSEPAS.
9. AJAX & RIA. 2 Motto: O! call back yesterday, bid time return. — William Shakespeare.
Browsers and Servers CGI Processing Model ( Common Gateway Interface ) © Norman White, 2013.
HTML Form Processing Learning Web Design – Chapter 9, pp Squirrel Book – Chapter 11, pp
XMLHttpRequest Object and XML What we should learn in this lesson –What is the XHR object? –How to create the XHR objects? –XHR object properties –XHR.
1 The World Wide Web. 2  Web Fundamentals  Pages are defined by the Hypertext Markup Language (HTML) and contain text, graphics, audio, video and software.
CSCI 323 – Web Development Chapter 1 - Setting the Scene We’re going to move through the first few chapters pretty quick since they are a review for most.
Lecture 3 – Data Storage with XML+AJAX and MySQL+socket.io
Interactive Web Application with AJAX
Ajax (Asynchronous JavaScript and XML). AJAX  Enable asynchronous communication between a web client and a server.  A client is not blocked when an.
Ajax Basics The XMLHttpRequest Object. Ajax is…. Ajax is not…. Ajax is not a programming language. Ajax is not a programming language. Ajax is a methodology.
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
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.
Intro to Ajax Fred Stluka Jan 25, /25/2006Intro to AjaxFred Stluka2 What is Ajax? "Asynchronous JavaScript and XML" New name for an old technique:
06/10/2015AJAX 1. 2 Introduction All material from AJAX – what is it? Traditional web pages and operation Examples of AJAX use Creating.
Ajax In Action The Journey into Web2.0 Presented by Eric Pascarello.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
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.
Introduction to JavaScript CS101 Introduction to Computing.
Asynchronous Javascript And XML AJAX : an introduction UFCEUS-20-2 : Web Programming.
School of Computing and Information Systems CS 371 Web Application Programming AJAX.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
AJAX Asynchronous JavaScript & XML A short introduction.
Modifying HTML attributes and CSS values. Learning Objectives By the end of this lecture, you should be able to: – Select based on a class (as opposed.
INT222 - Internet Fundamentals Shi, Yue (Sunny) Office: T2095 SENECA COLLEGE.
AJAX Asynchronous JavaScript and XML 1. AJAX Outline What is AJAX? Benefits Real world examples How it works 2.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
CHAPTER 8 AJAX & JSON WHAT IS AJAX? Ajax lets you…
AJAX AJAX Asynchronous JavaScript and XML --- MADHAVI
AJAX – Asynchronous JavaScript And XML By Kranthi Kiran Nuthi CIS 764 Kansas State University.
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.
AJAX CS456 Fall Examples Where is AJAX used? Why do we care?
1 AJAX. AJAX – Whatzit? Asynchronous (content loading)‏ Javascript (logic & control)‏ And XML (request handling)‏
JQUERY AND AJAX
JavaScript and Ajax Week 10 Web site:
NCCUCS 軟體工程概論 Lecture 5: Ajax, Mashups April 29, 2014.
AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library.
Introduction to. Learning Objectives By the end of this lecture, you should be able to: – Describe the difference between client-side and server-side.
Tonga Institute of Higher Education IT 141: Information Systems
JavaScript and Ajax (Ajax Tutorial)
CSE 154 Lecture 11: AJAx.
Not a Language but a series of techniques
AJAX AJAX = Asynchronous JavaScript and XML.
CS 371 Web Application Programming
Data Virtualization Tutorial… CORS and CIS
XMLHttp Object.
PHP / MySQL Introduction
Intro to PHP & Variables
Web System & Technology
CSE 154 Lecture 11: AJAx.
AJAX and JSP ISYS 350.
Topic 5: Communication and the Internet
CSE 154 Lecture 22: AJAX.
AJAX Robin Burke ECT 360.
ISC440: Web Programming 2 AJAX
JavaScript & jQuery AJAX.
Chengyu Sun California State University, Los Angeles
AJAX CS-422 Dick Steflik.
Web Technology Even Sem 2015
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
AJAX and JSP ISYS 350.
Communicating with the Server
* Web Servers/Clients * The HTTP Protocol
Presentation transcript:

Ajax - Part II Communicating with the Server

Learning Objectives By the end of this lecture, you should be able to: – Describe the overview of steps involved in communicating with the web server for an AJAX cycle – Describe what is meant by a ‘callback’ function – List and define some of the more common ‘status response’ messages that come from a server – Describe what is meant by the ‘A’ in AJAX – Describe the kinds of tasks typically handled by a server-side script

Steps in communicating with the web server There are a few steps involved in setting up an AJAX communication with the server. Here is the overview: Obtain a copy of the ‘ XMLHttpRequest object’. Use this object to specify the kind of data you are going to send and where the data should go. Write a “callback” function to handle whatever information is received back from the browser (e.g. part of an HTML file, a query result from a database, etc) and update the web page. Send the request to the server. Examine the response from the server for other relevant data. The main point of Ajax is to let JavaScript talk to and get information from the server. Most of the time, that means there’s another script running on the web server that completes tasks JavaScript can’t do, like reading information from a database, sending off an , or logging a user in.

1: Obtain a copy of the ‘ XMLHttpRequest object’. We will use this object to make our connection to the web server and to pass information back and forth between the web server and the web client. Because the name is such a mouthful, most programmers refer to XMLHttpRequest object simply as the ‘XHR’ In JS, the code to obtain a copy of this object is: var newXHR = new XMLHttpRequest(); Coding with the XHR object is one of those situations rife with opportunity for cross- browser compatibility issues. Therefore, this is one of those cases where a library such as jQuery can really come to the rescue…

A brief aside: Not much ‘XML’ going on… In spite of the name, XMLHttpRequest there is not much XML that gets sent to or received from the server. At one point, XML was the ‘hot’ markup language – some said it was going to replace HTML as the web markup language of choice. In recent years, however, other tools have emerged to fill the void and while XML does have its uses, and is still very much around, it is not used nearly as widely as other standards. Therefore, while we will not be using the XMLHttpRequest object to work with XML, the object is still extremely helpful to web programmers as it has lots of functionality built in to it for communications with the server. From W3 Schools

2: Specify the kind of data to send, where to send it newXHR.open('GET', 'books.php?isbn= &author=Angelou'); We invoke a function called open() to: – Specify the method used to send data (‘ POST ’ or ‘ GET ’) – Specify the file to connect to (e.g. books.php ) – Often, we append to the URL, the data that we wish to send to the server (e.g. isbn= ) IMPORTANT: For security reasons, the file that is specified in the open() method MUST reside on the same web server as the file from which the request is originating. In other words, you can’t place your file on a DePaul web server and try to run a script that resides on Amazon’s web server.

3. Create a “callback” function to handle the results After processing the incoming request from a web client, the server will typically respond in some way. For example: – Output the results of a database query (e.g. the results of searching for authors with last name of ‘Rowling’) – Confirmation that a form was successfully processed ‘Thanks for joining our mailing list! ‘You have successfully updated your phone number.’ etc Your callback function should process the results that get returned from the query in some way. For example, you might take the information that came back regarding all books by an author named ‘Rowling’ and place them in a div section called ‘results’. You might format the results in an HTML list with each author in bold and the title of the book in italics, etc, etc. – Because this callback function is executed on the client, this function is nearly always written in JavaScript (or jQuery). Callback Function

4. Send the request At this point, we have set everything up. We now invoke the function send() which is where we “push the button” and send the request off to the server. To invoke send() we use our old friend the XHR object. There are two ways of invoking this method depending on whether we used ‘GET’ or ‘POST’ in step #2. – If we used GET, then: newXHR.send(null); – If we used POST, then: newXHR.send( query string goes here ) Recall that with POST I said that we send the information elsewhere. One place we can send it is when we invoke the send() function: newXHR.send('isbn= '); As it turns out, however, jQuery also makes this step much simpler.

5. Receive the response Recall the callback function we created in step 3. Once the response has been received from the server, the callback function jumps into action and processes that response. The server’s response is packaged up in a tidy little bundle and attached to the XHR object. You can use a method of the XHR object called responseText() to access this information: var responseString; responseString = newXHR.responseText(); This response string contains the ‘relevant’ information such as the response to a user’s query about the weather forecast in Chicago. In addition to the specific information that the user is interested in, the server also bundles into the XHR object the status of the response. We will discuss this ‘status response’ momentarily. – A competent web designer will nearly always include some code to examine the status of the response to ensure that there were no unexpected problems.

Completion of One Cycle That ends one iteration of the AJAX cycle. It is entirely possible, however, that there are multiple AJAX cycles going on at the same time on different parts of a single web page. We will now examine in slightly more detail, a couple of the topics from the previous steps. Refer back to the overview of these steps as we proceed. Callback Function

Status Response Recall from earlier: In addition to the specific information that the user is interested in, the server also bundles into the XHR object the status of the response. Some examples of the status response are shown here. You have almost certainly seen examples of these from time to time. 404 NOT FOUND – This means that the file requested by the client was not found. 401 UNAUTHORIZED – This means that the requested file requires authentication such as a login and password, but it was not provided. 200 OK – This response indicates that the request was processed without any problems. There are many other status responses. Your callback function could have some if/else type of code in there that springs into action in response to one or more of these responses. For example, you could write a “friendlier” version of the standard 401 error message than the standard one built into your browser.

Here is a somewhat typical 401 status response: Here is one that supposedly was once on the site of NY mayor MichaelBloomberg.com: Personally, I’d recommend a happy medium between these two versions. Status Response Examples

Simple example: Ajax Example function loadXMLDoc() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } Let AJAX change this text Change Content See: Note: To run this scrip,t you must use the URL listed here. You can not run the script from your own computer unless you have your own server and server-side script set up. Other XHR properties to be aware of include onreadystatechange, readyState, and status. We will discuss these shortly. Source code is: first_ajax.htm

The ‘A’ in AJAX The ‘A’ stands for ‘Asynchronous’ To explain why this is helpful, consider what the server needs to do in responding to a typical request: – Parse the incoming message – Open a connection to the database – Query the database – Form a response – Send the response to the client ‘Asynchronous’ refers to the client. It means that once your client has sent the request off to the server, the client’s script does NOT have to wait for the server’s response. Instead, this script (along with any other scripts on your page) can continue to be executed. The ability for scripts to function asynchronously can at times significantly increase the speed and efficiency of your pages.

GET v.s. POST These are the two commonly used methods to send and receive data between the client and the server. POST is typically used when you plan to update information on the server (e.g. add information from a ‘Join Mailing List’ form on the client to a database on the server). GET is typically used when you plan to receive information back from the user such as if you have requested information about a book on Amazon.com. With ‘GET’, the data being sent TO the server is usually appended to the end of the URL. Note in the example above, the ‘?’ after the URL, immediately after which is the info we wish to pass to the server. With ‘POST’, the data is sent separately from the URL by invoking a different function, e.g. ‘ post() ’.

What happens on the server? The file on the server (e.g. books.php ) will most likely contain a script that is ready to process the information that has just come in from the client. The script on the server is typically not JavaScript. These days, one of the most common and popular server-side scripting languages is PHP. – Server-side scripting languages typically specialize in things like connecting to databases, forming database queries, parsing and breaking down long strings into information, etc.

XMLHttpRequest Simple object with only a few methods and properties, but very functional: open() - opens the connection to a given URL setRequestheader() - adds a label/value pair to the header request send() - request is sent getAllResponseHeaders() - returns all HTTP response headers as a string getResponseHeader() - returns the specific HTTP header abort() - aborts the current request

XMLHttpRequest.open() HTTP method list GET - request data from the server POST - posts data to the server DELETE - deletes data for the given resource PUT - stores data for the given resource HEAD - similar to GET, but doesn't return the response body.

Key properties of the XMLHttpRequest Object onreadystatechange - holds a handle to the function called when the ready state of the request changes readyState - » 0 - uninitialized request » 1 - for open request » 2 - for a request that’s been sent » 3 - response received » 4 - response finished loading (this is what we look for) responseText - response as text responseXML - response as XML status - returns request status (404, 500 or 200) statusText - text associated with request status xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; }

Simple example - Revisited: Ajax Example function loadXMLDoc() { if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send(); } Let AJAX change this text Change Content

Another example: ch14-02.php THIS IS THE PHP SCRIPT THAT IS STORED AND EXECUTED ON THE SERVER <?php //If no search string is passed, then we can't search if(empty($_REQUEST['state'])) { echo "No State Sent"; } else { //Remove whitespace from beginning & end of passed search. $search = trim($_REQUEST['state']); switch($search) { case "MO" : $result = " St. Louis ". " Kansas City "; break; case "WA" : $result = " Seattle ". " Spokane ". " Olympia "; break; case "CA" : $result = " San Francisco ". " Los Angeles ". " Web 2.0 City ". " BarCamp "; break; case "ID" : $result = " Boise "; break; default : $result = "No Cities Found"; break; } echo " Cities: ". $result. " "; } ?> See: Note: As before, to run this script, you must use the URL listed here. You can not run the script from your own computer unless you have your own server and server-side script set up. Source code is: 02_ajax.htm PHP Script is: ch14-02.php

AJAX s jQuery You may have noticed that there is quite a lot of overhead (creating the XHR object, opening the connection to the server, sending the request using send(), retrieving the response using the XHR object) involved in setting up a basic AJAX cycle. All of these steps are necessary for every AJAX cycle. Yet nearly all of the “good stuff” happens inside the callback function (step #3). In addition, many of these steps are fraught with cross-browser compatibility issues. jQuery not only simplifies and shortens these steps, but it also heads off many potential cross-browser issues. You will be receiving several lectures on jQuery in the upcoming weeks.