SlideShare a Scribd company logo
1 of 55
JavaScript, Sixth Edition
Chapter 11
Updating Web Pages with Ajax
JavaScript, Sixth Edition 2
Objectives
When you complete this chapter, you will be able to:
• Describe the steps involved in using Ajax to update
data
• Create an HTTP request and interpret an HTTP
response
• Request and receive server data using the
XMLHttpRequest object
• Process data received from a web service and add it
to the DOM
• Update app data using JSON-P
JavaScript, Sixth Edition 3
Introduction to Ajax
• Allows client web pages to quickly interact and
exchange data with a web server
• Without reloading entire web page
• Relies on
– Programming language such as JavaScript
– Data interchange format such as JSON or XML
JavaScript, Sixth Edition 4
Introduction to Ajax (cont’d.)
• XMLHttpRequest object (XHR object)
– Uses HTTP to exchange data between a client
computer and a web server
– Can be used to request and receive data without
reloading a web page
JavaScript, Sixth Edition 5
Introduction to Ajax (cont’d.)
• Combining XMLHttpRequest with DHTML
– Allows update and modification to individual portions
of a web page
• With data received from a web server
• Google search suggestions
– One of the first commercial Ajax applications
Figure 11-1 Google search suggestions provided using Ajax
JavaScript, Sixth Edition 6
Figure 11-2 Standard HTTP request
Introduction to Ajax (cont’d.)
JavaScript, Sixth Edition 7
Figure 11-3 HTTP request with the XHR object
Introduction to Ajax (cont’d.)
JavaScript, Sixth Edition 8
Understanding the Limitations of Ajax
• Data requested can be located on a third-party
server
– Not all web servers or browsers support this
• Can use a server-side script as a proxy to access
data from another domain
• Proxy
– Server that acts for or performs requests for other
clients and servers
JavaScript, Sixth Edition 9
Accessing Content on a Separate
Domain
• Web service
– Data source made available on one domain for use
on other domains across web
– Does not contain graphical user interface or
command-line interface
– Simply provides services and data in response to
requests
• Up to the client to provide an implementation for a
program calling a web service
– Often requires API key
• Unique identifier assigned by service to each
person/organization that wants access
JavaScript, Sixth Edition 10
Accessing Content on a Separate
Domain (cont'd.)
• Proxy scripts often written in PHP
– Language specifically designed to run on web servers
JavaScript, Sixth Edition 11
Running Ajax from a Web Server
• Must open Ajax files from a web server
– With the HTTP (http://) or HTTPS (https://) protocol
• Can install server software on any computer
• Popular web server software
– Apache HTTP Server
– Nginx ("engine-ex")
– Microsoft Internet Information Services (IIS)
JavaScript, Sixth Edition 12
Working with HTTP
• Using Ajax to update data involves 4 steps:
1. Instantiate an XMLHttpRequest object for the web
browser where the script will run.
2. Use the XMLHttpRequest object to send a request
to the server.
3. Receive the response from the server containing the
requested data.
4. Process the data returned from the server, and
incorporate the data into the app.
JavaScript, Sixth Edition 13
Working with HTTP (cont'd.)
Figure 11-6 Using Ajax to update data
JavaScript, Sixth Edition 14
Working with HTTP (cont'd.)
Figure 11-7 Using Ajax with a proxy server to update data
JavaScript, Sixth Edition 15
Working with HTTP (cont'd.)
• Request
– Process of asking for a web page from a web server
• Response
– Web server’s reply
• Uniform Resource Locator (URL)
– A web page's unique address
– Consists of two parts
• Protocol (usually HTTP)
• Web server’s domain name or a web server’s Internet
Protocol address
JavaScript, Sixth Edition 16
Working with HTTP (cont’d.)
• Hypertext Transfer Protocol (HTTP)
– Set of rules defining how requests made by an HTTP
client to an HTTP server
– Defines how responses returned from an HTTP
server to an HTTP client
• HTTP client
– Refers to an application (web browser) making the
request
• HTTP server (another name for a web server)
– Refers to a computer that receives HTTP requests
and returns responses to HTTP clients
JavaScript, Sixth Edition 17
Working with HTTP (cont’d.)
• Host
– Computer system being accessed by a remote
computer
• W3C and Internet Engineering Task Force jointly
develop HTTP
– Version 1.1: most recent version of HTTP commonly
used today
– Version 2.0: in development
• Modern browser already support some features
JavaScript, Sixth Edition 18
Understanding HTTP Messages
• HTTP messages
– HTTP client requests and server responses
• HTTP client opens a connection to the server
– Submits a request message
– Web server returns a response message appropriate
to the request type
• Format:
Start line (request method or status returned)
Header lines (zero or more)
Blank line
Message body (optional)
JavaScript, Sixth Edition 19
Understanding HTTP Messages
(cont’d.)
• Headers
– Define information about the request or response
message and about the contents of the message
body
• 47 HTTP 1.1 headers
– generic headers used in request or response
messages
– headers specific to a request, response, or message
body
• Format for using a header
header: value
JavaScript, Sixth Edition 20
Understanding HTTP Messages
(cont’d.)
• 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
JavaScript, Sixth Edition 21
Understanding HTTP Messages
(cont’d.)
• Blank line always follows last header line
– Optional: message body can follow the blank line in
the messages
• Most common types of HTTP requests
– GET and POST
• Other HTTP request methods
– HEAD, DELETE, OPTIONS, PUT, and TRACE
• Can use browser tools to examine HTTP headers
JavaScript, Sixth Edition 22
Sending HTTP Requests
• GET method
– Used for standard web page requests
– Can have a query string or form data appended to the
URL
• POST request
– Similar to a GET request except that any submitted
data is included in the message body
• Immediately following the blank line after the last
header
JavaScript, Sixth Edition 23
Table 11-1 Common request headers
Sending HTTP Requests (cont’d.)
JavaScript, Sixth Edition 24
Table 11-2 Common message body headers
Sending HTTP Requests (cont’d.)
JavaScript, Sixth Edition 25
Receiving HTTP Responses
• HTTP response messages
– Take the same format as request messages
– Return 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
JavaScript, Sixth Edition 26
Receiving HTTP Responses (cont’d.)
– 5xx: (server error) - Request cannot be fulfilled
due to a server error
Table 11-3 Common response codes
JavaScript, Sixth Edition 27
Receiving HTTP Responses (cont’d.)
• Zero or more response headers follow the status
line
• Response returned from a server
– Can be much more involved than original request
that generated it
Table 11-4 Common response headers
JavaScript, Sixth Edition 28
Requesting Server Data
• XMLHttpRequest object
– Key to incorporating Ajax in JavaScript code
– Allows use of use JavaScript and HTTP to exchange
data between a web browser and a web server
JavaScript, Sixth Edition 29
Table 11-5 XMLHttpRequest object methods
Requesting Server Data (cont’d.)
JavaScript, Sixth Edition 30
Table 11-6 XMLHttpRequest object properties
Requesting Server Data (cont’d.)
JavaScript, Sixth Edition 31
Instantiating an XMLHttpRequest
Object
• Use the XMLHttpRequest constructor
var httpRequest = new XMLHttpRequest();
• Originally created specifically to request XML data
–Name hasn't changed, but now capable of more
• Most JavaScript programmers use a series of
nested try/catch statements
• Opening and closing HTTP connections is a
bottleneck in page loading
–HTTP/1.1 automatically keeps the client-server
connection open unless it is specifically closed
• Can make Ajax programs faster by reusing an
instantiated XMLHttpRequest object
JavaScript, Sixth Edition 32
Instantiating an XMLHttpRequest
Object (cont’d.)
var curRequest = false;
var httpRequest;
function getRequestObject() {
try {
httpRequest = new XMLHttpRequest();
}
catch (requestError) {
document.getElementById("main").innerHTML = "Your↵
browser does not support this content";
return false;
}
return httpRequest;
}
JavaScript, Sixth Edition 33
Opening and Sending a Request
• Use the open() method with the instantiated
XMLHttpRequest object
– To specify the request method (GET or POST) and
URL
• open() method accepts three optional arguments
– async, username, password
• abort() method
– Used to cancel any existing HTTP requests before
beginning a new one
JavaScript, Sixth Edition 34
Opening and Sending a Request
(cont’d.)
• send() method
– Submit the request to the server
– Accepts a single argument containing the message
body
• POST requests more involved
– Must manually build name-value pairs to submit
– Must submit at least Content-Type header before
send() method
– Also should submit Content-Length header and
Connection header
JavaScript, Sixth Edition 35
Receiving Server Data
• responseXML property
– Contains the HTTP response as an XML document
– Only if server response includes the Content-Type
header with a MIME type value of text/xml
• responseText property
– Contains the HTTP response as a text string
JavaScript, Sixth Edition 36
Processing XML Data in a Response
• Assign property values to document nodes
– Assign value of responseXML property to a variable
– Use innerHTML and node properties to assign
values of XML document stored in variable to
appropriate elements
JavaScript, Sixth Edition 37
Processing Text Data in a Response
• responseText value almost always a JSON string
– First use JSON.parse() to convert to object
– Then access property values of new object and add
to DOM elements
JavaScript, Sixth Edition 38
Sending and Receiving Synchronous
Requests and Responses
• Synchronous request
– Stops the processing of the JavaScript code until a
response returned from the server
• Check XMLHttpRequest object’s status property
value
– Ensure response received successfully
JavaScript, Sixth Edition 39
Sending and Receiving Synchronous
Requests and Responses (cont’d.)
• Synchronous responses
– Easier to handle
• Drawback
– Script will not continue processing until the response
is received
• Use asynchronous requests with the send()
method
JavaScript, Sixth Edition 40
Sending and Receiving Asynchronous
Requests and Responses
• Asynchronous request
– Allows JavaScript to continue processing while it
waits for a server response
• Create an asynchronous request
– Pass a value of true as the third argument of the
open() method
• Or omit the argument altogether
• Receive a response
– Use the XMLHttpRequest object’s readyState
property and onreadystatechange event
JavaScript, Sixth Edition 41
Sending and Receiving Asynchronous
Requests and Responses (cont’d.)
• Example:
stockRequest.abort();
stockRequest.open("get","StockCheck.php?" + "checkQuote=" +↵
tickerSymbol, true);
stockRequest.send(null);
stockRequest.onreadystatechange = fillStockInfo;
JavaScript, Sixth Edition 42
Sending and Receiving Asynchronous
Requests and Responses (cont’d.)
• Value assigned to the readyState property
– Updated automatically
• According to the current statement of the HTTP request
• If property assigned a value of 4
– Response finished loading
JavaScript, Sixth Edition 43
Sending and Receiving Asynchronous
Requests and Responses (cont’d.)
• Example:
function fillStockInfo() {
if (stockRequest.readyState === 4 && stockRequest.status↵
=== 200) {
var stockValues = stockRequest.responseText;
document.getElementById("ticker").innerHTML =↵
stockValues.ticker;
...
}
}
JavaScript, Sixth Edition 44
Refreshing Server Data Automatically
• Automatically refresh data obtained from an HTTP
server
– Use JavaScript’s setTimeout() or
setInterval() methods
• Send request to the server
• Read and process the data returned from the server
JavaScript, Sixth Edition 45
Creating Cross-Domain Requests
Without a Proxy Server
• Two alternatives to proxies for working around
same-origin policy
– JSON-P (JSON with padding)
• Requests JSON content using a script element
rather than an XHR object
– CORS (Cross-Origin Resource Sharing)
• Server sends special response header that indicates
data may be used on other domains
JavaScript, Sixth Edition 46
Creating Cross-Domain Requests
Without a Proxy Server (cont'd.)
Table 11-7 Comparison of XHR proxy, JSON-P, and CORS
JavaScript, Sixth Edition 47
Updating Content with JSON-P
• script element not subject to same-origin policy
• Program running on web server returns content
– JSON object treated as parameter for function call
– Called function processes JSON object
JavaScript, Sixth Edition 48
Updating Content with JSON-P
(cont'd.)
Figure 11-14 Using JSON-P to update data
JavaScript, Sixth Edition 49
Updating Content with JSON-P
(cont'd.)
• JSON-P URL generally consists of 2 parts:
– Request information
• URL of service, parameters
– Callback query string
• Keyword (usually "callback") & name of function to call
JavaScript, Sixth Edition 50
Updating Content with JSON-P
(cont'd.)
• JSON-P opens a security hole in your website
– If data source compromised, content you receive is a
potential attack route on your site
– Use JSON-P only with web service you trust
• JSON-P exposes API key or password to end users
– Use only with trusted users, such as employees
JavaScript, Sixth Edition 51
Updating Content with CORS
• Cross-domain request within an XHR object
• Part of XMLHttpRequest2 specification
– Additional properties, methods, and events for XHR
object
• Enables content provider to convey permission
– Access-Control-Allow-Origin HTTP response
header
• Value includes requesting domain
– XDomainRequest object (Microsoft)
• Must check first if browser defines this object
JavaScript, Sixth Edition 52
Summary
• Ajax allows data exchange with web server without
reloading page
• XMLHttpRequest object
– Uses HTTP to exchange data between a client
computer and a web server
• Proxy is common technique for working around
same-origin policy with Ajax
• HTTP defines rules for requests and responses
between client and server
JavaScript, Sixth Edition 53
Summary (cont’d.)
• Use methods and properties of an instantiated
XMLHttpRequest object with JavaScript
• First step to exchange data between an HTTP client
and a web server
– Instantiate an XMLHttpRequest object
• To improve performance
– Call the abort() method of the XMLHttpRequest
object
• Use the send() method with the instantiated
XMLHttpRequest object to submit the request to
the server
JavaScript, Sixth Edition 54
Summary (cont’d.)
• Server response assigned to responseXML or
responseText property
• Synchronous request stops the processing of the
JavaScript code until a response returned
• Asynchronous request allows JavaScript to continue
processing while waiting for a server response
• readystatechange event fires when value
assigned to readyState property changes
JavaScript, Sixth Edition 55
Summary (cont’d.)
• JSON with padding (JSON-P) requests JSON
content using script element rather than XHR
object
• Cross-Origin Resource Sharing (CORS)
– Server sends HTTP response header indicating data
may be used on other domains

More Related Content

What's hot

SQL - RDBMS Concepts
SQL - RDBMS ConceptsSQL - RDBMS Concepts
SQL - RDBMS ConceptsWebStackAcademy
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationWebStackAcademy
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data bindingMadhuri Kavade
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow BasicsPramod Singla
 
javaScript and jQuery
javaScript and jQueryjavaScript and jQuery
javaScript and jQueryMehrab Hossain
 
Hotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataHotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataMarco Gralike
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaPawanMM
 
For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.netTarun Jain
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerMarco Gralike
 
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow Transformations6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow TransformationsPramod Singla
 
BGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index StrategiesBGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index StrategiesMarco Gralike
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Design Concepts For Xml Applications That Will Perform
Design Concepts For Xml Applications That Will PerformDesign Concepts For Xml Applications That Will Perform
Design Concepts For Xml Applications That Will PerformMarco Gralike
 

What's hot (17)

SQL - RDBMS Concepts
SQL - RDBMS ConceptsSQL - RDBMS Concepts
SQL - RDBMS Concepts
 
Angular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and AuthorizationAngular - Chapter 9 - Authentication and Authorization
Angular - Chapter 9 - Authentication and Authorization
 
Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics5\9 SSIS 2008R2_Training - DataFlow Basics
5\9 SSIS 2008R2_Training - DataFlow Basics
 
Xml parsers
Xml parsersXml parsers
Xml parsers
 
javaScript and jQuery
javaScript and jQueryjavaScript and jQuery
javaScript and jQuery
 
Hotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured DataHotsos 2013 - Creating Structure in Unstructured Data
Hotsos 2013 - Creating Structure in Unstructured Data
 
JAXB
JAXBJAXB
JAXB
 
Ajax
AjaxAjax
Ajax
 
Session 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise JavaSession 24 - JDBC, Intro to Enterprise Java
Session 24 - JDBC, Intro to Enterprise Java
 
For Beginners - Ado.net
For Beginners - Ado.netFor Beginners - Ado.net
For Beginners - Ado.net
 
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File ServerUKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
UKOUG 2011 - Drag, Drop and other Stuff. Using your Database as a File Server
 
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow Transformations6.2\9 SSIS 2008R2_Training - DataFlow Transformations
6.2\9 SSIS 2008R2_Training - DataFlow Transformations
 
BGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index StrategiesBGOUG 2012 - XML Index Strategies
BGOUG 2012 - XML Index Strategies
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
REST Basics
REST BasicsREST Basics
REST Basics
 
Design Concepts For Xml Applications That Will Perform
Design Concepts For Xml Applications That Will PerformDesign Concepts For Xml Applications That Will Perform
Design Concepts For Xml Applications That Will Perform
 

Similar to JavaScript 6th Edition Ajax Chapter Summary

Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptxitzkuu01
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajaxRaja V
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohanWebVineet
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xmlsawsan slii
 
WEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxWEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxkarthiksmart21
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptMouDhara1
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptkstalin2
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Adnan Sohail
 
Ajax Technology
Ajax TechnologyAjax Technology
Ajax TechnologyZia_Rehman
 
Ajax Overview by Bally Chohan
Ajax Overview by Bally ChohanAjax Overview by Bally Chohan
Ajax Overview by Bally ChohanWebVineet
 

Similar to JavaScript 6th Edition Ajax Chapter Summary (20)

AJAX.pptx
AJAX.pptxAJAX.pptx
AJAX.pptx
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Introduction to ajax
Introduction to ajaxIntroduction to ajax
Introduction to ajax
 
Ajax tutorial by bally chohan
Ajax tutorial by bally chohanAjax tutorial by bally chohan
Ajax tutorial by bally chohan
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Ajax
AjaxAjax
Ajax
 
PHP - Introduction to PHP AJAX
PHP -  Introduction to PHP AJAXPHP -  Introduction to PHP AJAX
PHP - Introduction to PHP AJAX
 
Ajax and xml
Ajax and xmlAjax and xml
Ajax and xml
 
WEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptxWEB TECHNOLOGY Unit-5.pptx
WEB TECHNOLOGY Unit-5.pptx
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Servlet1.ppt
Servlet1.pptServlet1.ppt
Servlet1.ppt
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ajax
AjaxAjax
Ajax
 
Ajax Technology
Ajax TechnologyAjax Technology
Ajax Technology
 
Ajax
AjaxAjax
Ajax
 
Ajax
AjaxAjax
Ajax
 
Ajax Overview by Bally Chohan
Ajax Overview by Bally ChohanAjax Overview by Bally Chohan
Ajax Overview by Bally Chohan
 

More from Terry Yoast

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10Terry Yoast
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03Terry Yoast
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01Terry Yoast
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13Terry Yoast
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18Terry Yoast
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17Terry Yoast
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16Terry Yoast
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15Terry Yoast
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14Terry Yoast
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12Terry Yoast
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11Terry Yoast
 
9781337102087 ppt ch10
9781337102087 ppt ch109781337102087 ppt ch10
9781337102087 ppt ch10Terry Yoast
 
9781337102087 ppt ch09
9781337102087 ppt ch099781337102087 ppt ch09
9781337102087 ppt ch09Terry Yoast
 
9781337102087 ppt ch08
9781337102087 ppt ch089781337102087 ppt ch08
9781337102087 ppt ch08Terry Yoast
 
9781337102087 ppt ch06
9781337102087 ppt ch069781337102087 ppt ch06
9781337102087 ppt ch06Terry Yoast
 
9781337102087 ppt ch05
9781337102087 ppt ch059781337102087 ppt ch05
9781337102087 ppt ch05Terry Yoast
 
9781337102087 ppt ch04
9781337102087 ppt ch049781337102087 ppt ch04
9781337102087 ppt ch04Terry Yoast
 
9780538745840 ppt ch10
9780538745840 ppt ch109780538745840 ppt ch10
9780538745840 ppt ch10Terry Yoast
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09Terry Yoast
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08Terry Yoast
 

More from Terry Yoast (20)

9781305078444 ppt ch10
9781305078444 ppt ch109781305078444 ppt ch10
9781305078444 ppt ch10
 
9781305078444 ppt ch03
9781305078444 ppt ch039781305078444 ppt ch03
9781305078444 ppt ch03
 
9781305078444 ppt ch01
9781305078444 ppt ch019781305078444 ppt ch01
9781305078444 ppt ch01
 
9781337102087 ppt ch13
9781337102087 ppt ch139781337102087 ppt ch13
9781337102087 ppt ch13
 
9781337102087 ppt ch18
9781337102087 ppt ch189781337102087 ppt ch18
9781337102087 ppt ch18
 
9781337102087 ppt ch17
9781337102087 ppt ch179781337102087 ppt ch17
9781337102087 ppt ch17
 
9781337102087 ppt ch16
9781337102087 ppt ch169781337102087 ppt ch16
9781337102087 ppt ch16
 
9781337102087 ppt ch15
9781337102087 ppt ch159781337102087 ppt ch15
9781337102087 ppt ch15
 
9781337102087 ppt ch14
9781337102087 ppt ch149781337102087 ppt ch14
9781337102087 ppt ch14
 
9781337102087 ppt ch12
9781337102087 ppt ch129781337102087 ppt ch12
9781337102087 ppt ch12
 
9781337102087 ppt ch11
9781337102087 ppt ch119781337102087 ppt ch11
9781337102087 ppt ch11
 
9781337102087 ppt ch10
9781337102087 ppt ch109781337102087 ppt ch10
9781337102087 ppt ch10
 
9781337102087 ppt ch09
9781337102087 ppt ch099781337102087 ppt ch09
9781337102087 ppt ch09
 
9781337102087 ppt ch08
9781337102087 ppt ch089781337102087 ppt ch08
9781337102087 ppt ch08
 
9781337102087 ppt ch06
9781337102087 ppt ch069781337102087 ppt ch06
9781337102087 ppt ch06
 
9781337102087 ppt ch05
9781337102087 ppt ch059781337102087 ppt ch05
9781337102087 ppt ch05
 
9781337102087 ppt ch04
9781337102087 ppt ch049781337102087 ppt ch04
9781337102087 ppt ch04
 
9780538745840 ppt ch10
9780538745840 ppt ch109780538745840 ppt ch10
9780538745840 ppt ch10
 
9780538745840 ppt ch09
9780538745840 ppt ch099780538745840 ppt ch09
9780538745840 ppt ch09
 
9780538745840 ppt ch08
9780538745840 ppt ch089780538745840 ppt ch08
9780538745840 ppt ch08
 

Recently uploaded

ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfSpandanaRallapalli
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfphamnguyenenglishnb
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptxSherlyMaeNeri
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...Nguyen Thanh Tu Collection
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17Celine George
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Raw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptxRaw materials used in Herbal Cosmetics.pptx
Raw materials used in Herbal Cosmetics.pptx
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
ACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdfACC 2024 Chronicles. Cardiology. Exam.pdf
ACC 2024 Chronicles. Cardiology. Exam.pdf
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdfAMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
AMERICAN LANGUAGE HUB_Level2_Student'sBook_Answerkey.pdf
 
Judging the Relevance and worth of ideas part 2.pptx
Judging the Relevance  and worth of ideas part 2.pptxJudging the Relevance  and worth of ideas part 2.pptx
Judging the Relevance and worth of ideas part 2.pptx
 
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
HỌC TỐT TIẾNG ANH 11 THEO CHƯƠNG TRÌNH GLOBAL SUCCESS ĐÁP ÁN CHI TIẾT - CẢ NĂ...
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17How to Configure Email Server in Odoo 17
How to Configure Email Server in Odoo 17
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

JavaScript 6th Edition Ajax Chapter Summary

  • 1. JavaScript, Sixth Edition Chapter 11 Updating Web Pages with Ajax
  • 2. JavaScript, Sixth Edition 2 Objectives When you complete this chapter, you will be able to: • Describe the steps involved in using Ajax to update data • Create an HTTP request and interpret an HTTP response • Request and receive server data using the XMLHttpRequest object • Process data received from a web service and add it to the DOM • Update app data using JSON-P
  • 3. JavaScript, Sixth Edition 3 Introduction to Ajax • Allows client web pages to quickly interact and exchange data with a web server • Without reloading entire web page • Relies on – Programming language such as JavaScript – Data interchange format such as JSON or XML
  • 4. JavaScript, Sixth Edition 4 Introduction to Ajax (cont’d.) • XMLHttpRequest object (XHR object) – Uses HTTP to exchange data between a client computer and a web server – Can be used to request and receive data without reloading a web page
  • 5. JavaScript, Sixth Edition 5 Introduction to Ajax (cont’d.) • Combining XMLHttpRequest with DHTML – Allows update and modification to individual portions of a web page • With data received from a web server • Google search suggestions – One of the first commercial Ajax applications Figure 11-1 Google search suggestions provided using Ajax
  • 6. JavaScript, Sixth Edition 6 Figure 11-2 Standard HTTP request Introduction to Ajax (cont’d.)
  • 7. JavaScript, Sixth Edition 7 Figure 11-3 HTTP request with the XHR object Introduction to Ajax (cont’d.)
  • 8. JavaScript, Sixth Edition 8 Understanding the Limitations of Ajax • Data requested can be located on a third-party server – Not all web servers or browsers support this • Can use a server-side script as a proxy to access data from another domain • Proxy – Server that acts for or performs requests for other clients and servers
  • 9. JavaScript, Sixth Edition 9 Accessing Content on a Separate Domain • Web service – Data source made available on one domain for use on other domains across web – Does not contain graphical user interface or command-line interface – Simply provides services and data in response to requests • Up to the client to provide an implementation for a program calling a web service – Often requires API key • Unique identifier assigned by service to each person/organization that wants access
  • 10. JavaScript, Sixth Edition 10 Accessing Content on a Separate Domain (cont'd.) • Proxy scripts often written in PHP – Language specifically designed to run on web servers
  • 11. JavaScript, Sixth Edition 11 Running Ajax from a Web Server • Must open Ajax files from a web server – With the HTTP (http://) or HTTPS (https://) protocol • Can install server software on any computer • Popular web server software – Apache HTTP Server – Nginx ("engine-ex") – Microsoft Internet Information Services (IIS)
  • 12. JavaScript, Sixth Edition 12 Working with HTTP • Using Ajax to update data involves 4 steps: 1. Instantiate an XMLHttpRequest object for the web browser where the script will run. 2. Use the XMLHttpRequest object to send a request to the server. 3. Receive the response from the server containing the requested data. 4. Process the data returned from the server, and incorporate the data into the app.
  • 13. JavaScript, Sixth Edition 13 Working with HTTP (cont'd.) Figure 11-6 Using Ajax to update data
  • 14. JavaScript, Sixth Edition 14 Working with HTTP (cont'd.) Figure 11-7 Using Ajax with a proxy server to update data
  • 15. JavaScript, Sixth Edition 15 Working with HTTP (cont'd.) • Request – Process of asking for a web page from a web server • Response – Web server’s reply • Uniform Resource Locator (URL) – A web page's unique address – Consists of two parts • Protocol (usually HTTP) • Web server’s domain name or a web server’s Internet Protocol address
  • 16. JavaScript, Sixth Edition 16 Working with HTTP (cont’d.) • Hypertext Transfer Protocol (HTTP) – Set of rules defining how requests made by an HTTP client to an HTTP server – Defines how responses returned from an HTTP server to an HTTP client • HTTP client – Refers to an application (web browser) making the request • HTTP server (another name for a web server) – Refers to a computer that receives HTTP requests and returns responses to HTTP clients
  • 17. JavaScript, Sixth Edition 17 Working with HTTP (cont’d.) • Host – Computer system being accessed by a remote computer • W3C and Internet Engineering Task Force jointly develop HTTP – Version 1.1: most recent version of HTTP commonly used today – Version 2.0: in development • Modern browser already support some features
  • 18. JavaScript, Sixth Edition 18 Understanding HTTP Messages • HTTP messages – HTTP client requests and server responses • HTTP client opens a connection to the server – Submits a request message – Web server returns a response message appropriate to the request type • Format: Start line (request method or status returned) Header lines (zero or more) Blank line Message body (optional)
  • 19. JavaScript, Sixth Edition 19 Understanding HTTP Messages (cont’d.) • Headers – Define information about the request or response message and about the contents of the message body • 47 HTTP 1.1 headers – generic headers used in request or response messages – headers specific to a request, response, or message body • Format for using a header header: value
  • 20. JavaScript, Sixth Edition 20 Understanding HTTP Messages (cont’d.) • 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
  • 21. JavaScript, Sixth Edition 21 Understanding HTTP Messages (cont’d.) • Blank line always follows last header line – Optional: message body can follow the blank line in the messages • Most common types of HTTP requests – GET and POST • Other HTTP request methods – HEAD, DELETE, OPTIONS, PUT, and TRACE • Can use browser tools to examine HTTP headers
  • 22. JavaScript, Sixth Edition 22 Sending HTTP Requests • GET method – Used for standard web page requests – Can have a query string or form data appended to the URL • POST request – Similar to a GET request except that any submitted data is included in the message body • Immediately following the blank line after the last header
  • 23. JavaScript, Sixth Edition 23 Table 11-1 Common request headers Sending HTTP Requests (cont’d.)
  • 24. JavaScript, Sixth Edition 24 Table 11-2 Common message body headers Sending HTTP Requests (cont’d.)
  • 25. JavaScript, Sixth Edition 25 Receiving HTTP Responses • HTTP response messages – Take the same format as request messages – Return 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
  • 26. JavaScript, Sixth Edition 26 Receiving HTTP Responses (cont’d.) – 5xx: (server error) - Request cannot be fulfilled due to a server error Table 11-3 Common response codes
  • 27. JavaScript, Sixth Edition 27 Receiving HTTP Responses (cont’d.) • Zero or more response headers follow the status line • Response returned from a server – Can be much more involved than original request that generated it Table 11-4 Common response headers
  • 28. JavaScript, Sixth Edition 28 Requesting Server Data • XMLHttpRequest object – Key to incorporating Ajax in JavaScript code – Allows use of use JavaScript and HTTP to exchange data between a web browser and a web server
  • 29. JavaScript, Sixth Edition 29 Table 11-5 XMLHttpRequest object methods Requesting Server Data (cont’d.)
  • 30. JavaScript, Sixth Edition 30 Table 11-6 XMLHttpRequest object properties Requesting Server Data (cont’d.)
  • 31. JavaScript, Sixth Edition 31 Instantiating an XMLHttpRequest Object • Use the XMLHttpRequest constructor var httpRequest = new XMLHttpRequest(); • Originally created specifically to request XML data –Name hasn't changed, but now capable of more • Most JavaScript programmers use a series of nested try/catch statements • Opening and closing HTTP connections is a bottleneck in page loading –HTTP/1.1 automatically keeps the client-server connection open unless it is specifically closed • Can make Ajax programs faster by reusing an instantiated XMLHttpRequest object
  • 32. JavaScript, Sixth Edition 32 Instantiating an XMLHttpRequest Object (cont’d.) var curRequest = false; var httpRequest; function getRequestObject() { try { httpRequest = new XMLHttpRequest(); } catch (requestError) { document.getElementById("main").innerHTML = "Your↵ browser does not support this content"; return false; } return httpRequest; }
  • 33. JavaScript, Sixth Edition 33 Opening and Sending a Request • Use the open() method with the instantiated XMLHttpRequest object – To specify the request method (GET or POST) and URL • open() method accepts three optional arguments – async, username, password • abort() method – Used to cancel any existing HTTP requests before beginning a new one
  • 34. JavaScript, Sixth Edition 34 Opening and Sending a Request (cont’d.) • send() method – Submit the request to the server – Accepts a single argument containing the message body • POST requests more involved – Must manually build name-value pairs to submit – Must submit at least Content-Type header before send() method – Also should submit Content-Length header and Connection header
  • 35. JavaScript, Sixth Edition 35 Receiving Server Data • responseXML property – Contains the HTTP response as an XML document – Only if server response includes the Content-Type header with a MIME type value of text/xml • responseText property – Contains the HTTP response as a text string
  • 36. JavaScript, Sixth Edition 36 Processing XML Data in a Response • Assign property values to document nodes – Assign value of responseXML property to a variable – Use innerHTML and node properties to assign values of XML document stored in variable to appropriate elements
  • 37. JavaScript, Sixth Edition 37 Processing Text Data in a Response • responseText value almost always a JSON string – First use JSON.parse() to convert to object – Then access property values of new object and add to DOM elements
  • 38. JavaScript, Sixth Edition 38 Sending and Receiving Synchronous Requests and Responses • Synchronous request – Stops the processing of the JavaScript code until a response returned from the server • Check XMLHttpRequest object’s status property value – Ensure response received successfully
  • 39. JavaScript, Sixth Edition 39 Sending and Receiving Synchronous Requests and Responses (cont’d.) • Synchronous responses – Easier to handle • Drawback – Script will not continue processing until the response is received • Use asynchronous requests with the send() method
  • 40. JavaScript, Sixth Edition 40 Sending and Receiving Asynchronous Requests and Responses • Asynchronous request – Allows JavaScript to continue processing while it waits for a server response • Create an asynchronous request – Pass a value of true as the third argument of the open() method • Or omit the argument altogether • Receive a response – Use the XMLHttpRequest object’s readyState property and onreadystatechange event
  • 41. JavaScript, Sixth Edition 41 Sending and Receiving Asynchronous Requests and Responses (cont’d.) • Example: stockRequest.abort(); stockRequest.open("get","StockCheck.php?" + "checkQuote=" +↵ tickerSymbol, true); stockRequest.send(null); stockRequest.onreadystatechange = fillStockInfo;
  • 42. JavaScript, Sixth Edition 42 Sending and Receiving Asynchronous Requests and Responses (cont’d.) • Value assigned to the readyState property – Updated automatically • According to the current statement of the HTTP request • If property assigned a value of 4 – Response finished loading
  • 43. JavaScript, Sixth Edition 43 Sending and Receiving Asynchronous Requests and Responses (cont’d.) • Example: function fillStockInfo() { if (stockRequest.readyState === 4 && stockRequest.status↵ === 200) { var stockValues = stockRequest.responseText; document.getElementById("ticker").innerHTML =↵ stockValues.ticker; ... } }
  • 44. JavaScript, Sixth Edition 44 Refreshing Server Data Automatically • Automatically refresh data obtained from an HTTP server – Use JavaScript’s setTimeout() or setInterval() methods • Send request to the server • Read and process the data returned from the server
  • 45. JavaScript, Sixth Edition 45 Creating Cross-Domain Requests Without a Proxy Server • Two alternatives to proxies for working around same-origin policy – JSON-P (JSON with padding) • Requests JSON content using a script element rather than an XHR object – CORS (Cross-Origin Resource Sharing) • Server sends special response header that indicates data may be used on other domains
  • 46. JavaScript, Sixth Edition 46 Creating Cross-Domain Requests Without a Proxy Server (cont'd.) Table 11-7 Comparison of XHR proxy, JSON-P, and CORS
  • 47. JavaScript, Sixth Edition 47 Updating Content with JSON-P • script element not subject to same-origin policy • Program running on web server returns content – JSON object treated as parameter for function call – Called function processes JSON object
  • 48. JavaScript, Sixth Edition 48 Updating Content with JSON-P (cont'd.) Figure 11-14 Using JSON-P to update data
  • 49. JavaScript, Sixth Edition 49 Updating Content with JSON-P (cont'd.) • JSON-P URL generally consists of 2 parts: – Request information • URL of service, parameters – Callback query string • Keyword (usually "callback") & name of function to call
  • 50. JavaScript, Sixth Edition 50 Updating Content with JSON-P (cont'd.) • JSON-P opens a security hole in your website – If data source compromised, content you receive is a potential attack route on your site – Use JSON-P only with web service you trust • JSON-P exposes API key or password to end users – Use only with trusted users, such as employees
  • 51. JavaScript, Sixth Edition 51 Updating Content with CORS • Cross-domain request within an XHR object • Part of XMLHttpRequest2 specification – Additional properties, methods, and events for XHR object • Enables content provider to convey permission – Access-Control-Allow-Origin HTTP response header • Value includes requesting domain – XDomainRequest object (Microsoft) • Must check first if browser defines this object
  • 52. JavaScript, Sixth Edition 52 Summary • Ajax allows data exchange with web server without reloading page • XMLHttpRequest object – Uses HTTP to exchange data between a client computer and a web server • Proxy is common technique for working around same-origin policy with Ajax • HTTP defines rules for requests and responses between client and server
  • 53. JavaScript, Sixth Edition 53 Summary (cont’d.) • Use methods and properties of an instantiated XMLHttpRequest object with JavaScript • First step to exchange data between an HTTP client and a web server – Instantiate an XMLHttpRequest object • To improve performance – Call the abort() method of the XMLHttpRequest object • Use the send() method with the instantiated XMLHttpRequest object to submit the request to the server
  • 54. JavaScript, Sixth Edition 54 Summary (cont’d.) • Server response assigned to responseXML or responseText property • Synchronous request stops the processing of the JavaScript code until a response returned • Asynchronous request allows JavaScript to continue processing while waiting for a server response • readystatechange event fires when value assigned to readyState property changes
  • 55. JavaScript, Sixth Edition 55 Summary (cont’d.) • JSON with padding (JSON-P) requests JSON content using script element rather than XHR object • Cross-Origin Resource Sharing (CORS) – Server sends HTTP response header indicating data may be used on other domains