Modern JavaScript Develop And Design Instructor’s Notes Chapter 11– Ajax Modern JavaScript...
-
Upload
glenn-wigington -
Category
Documents
-
view
221 -
download
2
Transcript of Modern JavaScript Develop And Design Instructor’s Notes Chapter 11– Ajax Modern JavaScript...
Modern JavaScriptDevelop And Design
Instructor’s NotesChapter 11– Ajax
Modern JavaScript Design And DevelopCopyright © 2012 by Larry Ullman
Objectives
• Explain what Ajax is• Create a browser-neutral Ajax
object• Setup an Ajax request• Perform an Ajax request• Test for a request’s completeness
More Objectives
• Send data to a server-side resource• Handle different types of data
returned by the server• Create a PHP script that returns
different types of data• Implement several real-world Ajax
examples
Making Ajax Requests
1. Create an Ajax object2. Prepare the request3. Make the request4. Handle the response
Creating the Ajax Objectfunction getXMLHttpRequestObject() { var ajax = null;
// Most browsers: if (window.XMLHttpRequest) { ajax = new XMLHttpRequest(); } else if (window.ActiveXObject) { // Older IE. ajax = new ActiveXObject('MSXML2.XMLHTTP.3.0'); } // Return the object: return ajax;
} // End of getXMLHttpRequestObject() function.
Identifying the Result Handler
ajax.onreadystatechange = handleStateChange;
Making the Request
GET• Used to fetch data• Common and
repeatable
POST• Intended to cause a
server change or reaction
• Should be unique
ajax.open('GET', 'http://www.example.com/page.php', true);ajax.send(null);
The Resource
• Can use absolute or relative path• Must be on the same domain• Must be over HTTP (or other
Internet protocol)
The readyState
• 0, unset• 1, opened• 2, headers received• 3, loading• 4, done
if (ajax.readyState == 4) { // Handle the response.} else { // Show the 'Loading...' message or do nothing.}
The status
• 2xx, OK• 301, Moved Permanently• 304, Not Modified• 401, Unauthorized
if (ajax.readyState == 4) { if ( (ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304) ) { // Handle the response. } else { // Status error! }}
The Response
• responseXML• responseText
document.getElementById('output').innerHTML = ajax.responseText;
Sending Data via GET
• Append to URL• Provide to send()
ajax.open('GET', 'http://www.example.com/somepage.php?id=' + encodeURIComponent(id), true);
var data = 'email=' + encodeURIComponent(email) + '&password=' + encodeURIComponent(password);ajax.open('GET', 'http://www.example.com/somepage.php', true);ajax.send(data);
Sending Data via POST
var data = 'email=' + encodeURIComponent(email) + '&password=' + encodeURIComponent(password);ajax.open('POST', 'http://www.example.com/somepage.php', true);ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');ajax.send(data);
Debugging Steps
• Test the server-side resource directly
• Use a network monitor• Verify the response data• Watch for caching!
Data Formats
• Plain text• eXtensible Markup Language (XML)• JavaScript Object Notation (JSON)
Handling XML
<book> <chapter id="1">(Re-)Introducing JavaScript</chapter> <chapter id="2">JavaScript in Action</chapter></book>
var data = ajax.responseXML;var chapters = data.getElementsByTagName('chapter');for (var i = 0, count = chapters.length; i < count; i++) { // Use chapters[i].getAttribute('id') // Use chapters[i].firstChild.nodeValue}
Handling JSON
{"1": {"title": "(Re-)Introducing JavaScript"},"2": {"title": "JavaScript in Action"}}
var data = ajax.responseText;var data = JSON.parse(data);data[2].title; // JavaScript in Action
Server-Side Scripts
• May receive input via GET or POST• Returns output
– Plain text– XML– JSON
• Generally does not return HTML (unless the data is HTML)
Sending Plain Text
<?php // Nothing before this!echo 'This is some text being printed';?>
<?phpif (/* username is available */) { echo 'AVAILABLE';} else { echo 'UNAVAILABLE';}?>
Sending XML
<?php // Nothing before this!header('Content-Type: text/xml');echo '<?xml version="1.0" encoding="utf-8" standalone="yes" ?>';echo '<comments>';$q = 'SELECT comment, email, date_submitted FROM comments ORDER BY date_submitted DESC';$r = mysqli_query($dbc, $q);while ($row = mysqli_fetch_array($r)) { echo "<record> <comment>{$row['comment']}</comment> <email>{$row['email']}</email> <date>{$row['date']}</>{$> </record>\n";}echo '</comments>';
Sending JSON
<?phpheader('Content-Type: application/json');$data = array();$q = 'SELECT comment, email, date_submitted FROM comments ORDER BY date_submitted DESC';$r = mysqli_query($dbc, $q);while ($row = mysqli_fetch_array($r)) { $data[] = $row;}echo json_encode($data);
Showing Progress
HTML:<img src="images/ajax-loader.gif" id="loader”>
CSS:#loader { visibility: hidden; }
JavaScript:loader.style.visibility = 'visible';ajax.open('GET', 'http://www.example.com/somepage.php', true);ajax.send(null);
JavaScript, when done:loader.style.visibility = 'hidden';
Login Submission
if ( (email.value.length > 0) && (password.value.length > 0) ) {
// Perform an Ajax request: var ajax = getXMLHttpRequestObject(); ajax.onreadystatechange = function() {} ajax.open('POST', 'resources/login.php', true); ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); var data = 'email=' + encodeURIComponent(email.value) + '&password=' + encodeURIComponent(password.value); ajax.send(data);
// Et cetera.