Download presentation
Presentation is loading. Please wait.
1
JavaScript & jQuery AJAX
2
Understanding HTTP COMMUNICATION
Request and response
3
Understanding HTTP Messages
HTTP transmission protocol consists of messages HTTP client requests and server responses HTTP client opens a connection to the server Submits a request message to the web server Web server returns a response message appropriate to the request type
4
Understanding HTTP Request Headers
All messages contain Headers Define information about the request or response message and about the contents of the message body Can use browser tools to examine HTTP headers Chrome-Developer tools-Network log
5
Common Request Headers
6
HTTP Cache-Control Header
Specifies how a web browser should cache any server content it receives Caching Temporary storage of data for faster access Web browser attempts to locate any necessary data in its cache Before making a request from a web server Goes against the reason for using Ajax Include Cache-Control: no-cache
7
HTTP Header Request Types
Most common types of HTTP requests GET Used for standard Web page requests Can have a query string or form data appended to the URL POST Similar to a GET request except that any data is sent as a separate packet
8
HTTP Responses HTTP response messages Status codes format
Take the same format as request messages Can be much more involved than original request that generated it Returns protocol and version of the HTTP server Along with a status code and descriptive text Status codes format 1xx: (informational) - Request received 2xx: (success) - Request successful 3xx: (redirection) - Request cannot be completed without further action 4xx: (client error) - Request cannot be fulfilled due to a client error 5xx: (server error) - Request cannot be fulfilled due to a server error
9
HTTP Response Data Data being returned to the web page
Types of data can be HTML JSON XML
10
HOW AJAX works
11
Introduction to AJAX (cont’d.)
Google Suggest list box uses AJAX when user starts typing in search request
12
Introducing AJAX AJAX (Asynchronous JavaScript and XML)
A programming technique for loading data into part of a web page on demand without having to load a new Web page or reload the current page Not a programming language a combination of several techniques (HTML, JavaScript, XML, and HTTP asynchronous communication) to create fully interactive Web applications Relies on Programming language such as JavaScript Data interchange format such as JSON or XML
13
Benefits User experience is improved Single page web applications
Use web-based tools that feel more like a software application, even though they run in a browser Less bandwidth
14
The Classic Web Application Model
Users interact with Web servers through a Web page loaded on their browser Pages are exchanged: one page is sent to server to request information another page is sent to client to report on results of the request Exchange of information is synchronous user sends a request and must wait for a response from the server before doing anything else
15
The AJAX Web Application Model
Communication is asynchronous User does not have to wait for a response from the server to do other tasks on the Web page Web page interacts with the AJAX engine using code written in JavaScript Engine communicates with the server using the same HTTP request protocol that the classic model employs to request/receive Web pages
16
Limitations of AJAX Requires JavaScript to be running on user’s browser If a user disables JavaScript on the browser for security reasons, AJAX applications are disabled Does not record user’s browser history cannot use browser’s Back button to retrieve information or bookmark information returned by AJAX If too many AJAX engines run simultaneously, making calls to the Web server, communication with the server may be compromised
17
Implementing ajax using Javascript or jQuery
18
Overview of Creating an AJAX Script
Steps to create an AJAX script Instantiate an XMLHttpRequest object for the Web browser where the script will run Use the XMLHttpRequest object to send a request to the server Receive the response from the server containing the requested data Process the data returned from the server, and incorporate the data into the app.
19
CREATING AND SENDING THE HTTP REQUEST
20
Creating the AJAX Request Object
To create and AJAX request, must use the XMLHttpRequest object To create an XMLHttpRequest object in either Javascript or jQuery: var myhttpRequest = new XMLHttpRequest();
21
Opening the AJAX communication line
The open() method specifies the server resource to access with the request object: req.open(method, url, async, user, pwd) The method parameter has two possible values: GET and POST The get method sends data to the Web server by attaching a field name/value pair to the URL The post method sends data in a separate stream from the URL (several advantages) If using post, must set Content-Type header before executing send() method myhttpRequest.open(“GET”,”datafile.txt”,true);
22
Building HTTP headers Depending on the type of data being requested, might need to specify HTTP headers myhttpRequest.setRequestHeader("Content-Type", "application/json"); myhttpRequest.setRequestHeader(" Cache-Control”, “no-cache”);
23
Sending the HTTP Request
The send() method sends data to the server: myhttpRequest.send( [content] ) Example: var someContent = { name: "Donald Duck", city: "Duckburg" }, myhttpRequest.send(someContent)
24
Completed Request example
var myReq = new XMLHttpRequest(); myReq.open(“get”, “datafile.txt”, true); myReq.send(); Note: true means it is an asynchronous request
25
ProcesSing the response
26
Processing the XMLHttpRequest Response
The state of the response is constantly changing until the response is complete Event Handler onreadystatechange – specifies the name of the event handler function that executes whenever the property readystate changes in value readystate property – contains one of the following values which represent the state of the HTTP request 0 – uninitialized - Request object is created 1 – open – open() method was called 2 – sent - Browser successfully sends the request using the send() method, but has received no response from the server 3 – receiving - Browser begins receiving a partial response from the server 4 – loaded - Server has completed sending a response to the browser (status property is 200)
27
Processing the XMLHttpRequest Response
readystate property gives information about the progress of the transmission status property confirms that the request was successfully handled by the server Both should be examined readystate = 4 and status=200 is successful
28
Processing the XMLHttpRequest Response using readyStateChange
To test when the server has responded to a request: req.onreadystatechange = function() { if (this.readystate == 4) { if (this.status = 200) { ..code to process returned data if any }
29
Processing the XMLHttpRequest Response using event listener
var xhr = new XMLHttpRequest(); // Create XMLHttpRequest object xhr.open('GET', 'data.html', true); // Prepare the request xhr.send(null); // Send the request //another way to test when the server has responded xhr.onload = function() { // When response has loaded, readystate=4 if(xhr.status === 200) { // If server status was ok ..code to process returned data if any }};
30
ProcesSing Returned Data
31
Data Common Data retrieved using AJAX HTML File JSON data XML data
RSS Feed syndications Data from Web services the type of data expected, dictates the response property to evaluate
32
IF THE DATA IS HTML DATA responseText property
Contains the HTTP response as a text string var xhr = new XMLHttpRequest(); xhr.onload = function() { if(xhr.status === 200) { document.getElementById('content').innerHTML = xhr.responseText; }}; xhr.open('GET', 'data.html', true); xhr.send(null);
33
IF THE DATA IS XML responseXML property
Contains the HTTP response as an XML document Must create element and attribute nodes Navigate through the node tree – it’s complicated! To retrieve an XML document object: var xmlDoc = req.responseXML To reference a collection of elements within the XML document: var elemArr = xmlDoc.getElementsByTagName(elem) To return text of an element in the collection: elemArr[i].firstChild.nodeValue
34
IF USING the jQuery Way Easier way to request data from the server with an HTTP GET or POST request. $.get(url,data,callback) $.post(url,data,callback) $("button").click(function(){ $.post("demo_test_post.asp", { name: "Donald Duck", city: "Duckburg" }, function(data, status){ alert("Data: " + data + "\nStatus: " + status); }); });
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.