AJAX Asynchronous Javascript And XML AJAX A lot

  • Slides: 28
Download presentation
AJAX Asynchronous Javascript And XML

AJAX Asynchronous Javascript And XML

AJAX • A lot of hype – It has been around for a while

AJAX • A lot of hype – It has been around for a while – Not complex • Powerful approach to building websites – Think differently • Allows for more interactive web applications – Gmail, docs. google. com, Flickr, ajax 13, etc.

ONE SHAKE PLEASE

ONE SHAKE PLEASE

AJAX Technologies • HTML – Used to build web forms and identify fields •

AJAX Technologies • HTML – Used to build web forms and identify fields • Javascript – Facilitates asynchronous communication and modification of HTML in-place • DHTML - Dynamic HTML – Additional markup for modifying and updating HTML • DOM - Document Object Model – Used via Javascript to work with both the structure of your HTML and also XML from the server

The XMLHttp. Request Object • Base object for AJAX – Used to make connections,

The XMLHttp. Request Object • Base object for AJAX – Used to make connections, send data, receive data, etc. • Allows your javascript code to talk back and forth with the server all it wants to, without the user really knowing what is going on. • Available in most browsers – But called different things

The XMLHttp. Request Object �script language="javascript" type="text/javascript"> < var request; function create. Request() {

The XMLHttp. Request Object �script language="javascript" type="text/javascript"> < var request; function create. Request() { try { request = new XMLHttp. Request(); if (request. override. Mime. Type) { request. override. Mime. Type('text/xml'); } } catch (trymicrosoft) { try { request = new Active. XObject("Msxml 2. XMLHTTP"); } catch (othermicrosoft) { try { request = new Active. XObject("Microsoft. XMLHTTP"); } catch (failed) { request = false; } } } if (!request) alert("Error initializing XMLHttp. Request!"); } </script>

Communicating • Steps – – – Gather information (possibly from HTML form) Set up

Communicating • Steps – – – Gather information (possibly from HTML form) Set up the URL Open the connection Set a callback method Send the request function get. Customer. Info() { var phone = document. get. Element. By. Id("phone"). value; var url = "/cgi-local/lookup. Customer. php? phone=" + escape(phone); request. open("GET", url, true); request. onreadystatechange = update. Page; request. send(null); }

Handling Server Responses • When the server responds, your callback method will be invoked.

Handling Server Responses • When the server responds, your callback method will be invoked. – It is called at various stages of the process – Test ready. State function update. Page() { if (request. ready. State == 4) { if (request. status == 200) { // Handle the response } else alert("status is " + request. status); } }

HTTP Ready States • 0: The request is uninitialized – Before calling open() •

HTTP Ready States • 0: The request is uninitialized – Before calling open() • 1: The request is set up, but hasn’t been sent – Before calling send() • 2: The request is sent and is being processed – Sometimes you can get content headers now • 3: The request is being processed – The server hasn’t finished with its response • 4: The response is complete

The XMLHttp. Request Object • Methods – abort() • cancel current request – get.

The XMLHttp. Request Object • Methods – abort() • cancel current request – get. All. Response. Headers() • Returns the complete set of http headers as a string – get. Response. Header(“headername”) • Return the value of the specified header – open(“method”, “URL”, async, “uname”, “passwd”) • Sets up the call – set. Request. Header(“label”, “value”) – send(content) • Actually sends the request

The XMLHttp. Request Object • Properties – onreadystatechange • Event handler for an event

The XMLHttp. Request Object • Properties – onreadystatechange • Event handler for an event that fires at every state change – ready. State • Returns the state of the object – response. Text • Returns the response as a string – response. XML • Returns the response as XML - use W 3 C DOM methods – status • Returns the status as a number - ie. 404 for “Not Found” – status. Text • Returns the status as a string - ie. “Not Found”

Typical AJAX Flow • Make the call – – – Gather information (possibly from

Typical AJAX Flow • Make the call – – – Gather information (possibly from HTML form) Set up the URL Open the connection Set a callback method Send the request • Handle the response (in callback method) – When request. ready. State == 4 and request. status == 200 – Get the response in either text or xml • request. response. Text or request. response. XML – Process the response appropriately for viewing – Get the objects on the page that will change • document. get. Element. By. Id or document. get. Element. By. Name, etc. – Make the changes

AJAX Response Handler function update. Page() { if (request. ready. State == 4) {

AJAX Response Handler function update. Page() { if (request. ready. State == 4) { if (request. status == 200) { var response = request. response. Text. split("|"); // “order|address” document. get. Element. By. Id("order"). value = response[0]; document. get. Element. By. Id("address"). inner. HTML = response[1]; } else alert("status is " + request. status); } }

Simple AJAX Example • Enter username • If you have been to the site

Simple AJAX Example • Enter username • If you have been to the site before – Say welcome back • Else – Say nice to meet you – Enter into list (perhaps) • ajaxform. html, ajax. js, ajax. php – http: //dna. cs. byu. edu/~snell/Classes/CS 360/simpleajax/ajaxform. html

function load. Map(filename) // Download the data in data. xml and load it on

function load. Map(filename) // Download the data in data. xml and load it on the map. The format we expect is: { // <markers> // <marker lat="37. 441" lng="-122. 141" note="marker notes"/> var request = GXml. Http. create(); // <marker lat="37. 322" lng="-121. 213" note="marker notes"/> request. open("GET", filename, true); // </markers> request. onreadystatechange = function() // <trail> // <point lat="37. 441" lng="-122. 141"/> { // <point lat="37. 322" lng="-121. 213"/> if (request. ready. State == 4) // </trail> { var xml. Doc = request. response. XML; var markers = xml. Doc. document. Element. get. Elements. By. Tag. Name("marker"); mapmarkers. length=0; for (var i = 0; i < markers. length; i++) { mapmarkers. push(create. Marker(new GLat. Lng(parse. Float(markers[i]. get. Attribute("lat")), parse. Float(marke map. add. Overlay(mapmarkers[i]); } map. set. Center(new GLat. Lng(parse. Float(markers[0]. get. Attribute("lat")), parse. Float(markers[0]. get. Attribute("lng mappoints. length = 0; var trailpoints = xml. Doc. document. Element. get. Elements. By. Tag. Name("point"); for (var i = 0; i < trailpoints. length; i++) { var tpoint = new GLat. Lng(parse. Float(trailpoints[i]. get. Attribute("lat")), parse. Float(trailpoints[i]. get. Attribute mappoints. push(tpoint); } map. add. Overlay(new GPolyline(mappoints)); } } request. send(null); }

AJAX Libraries • Prototype – http: //www. prototypejs. org/ • Scriptaculous – http: //script.

AJAX Libraries • Prototype – http: //www. prototypejs. org/ • Scriptaculous – http: //script. aculo. us/ • JQuery – http: //jquery. com/ • Mochikit – http: //mochikit. com/

Prototype Sample new Ajax. Request('/some_url', { method: 'get', on. Success: function(transport) { var response

Prototype Sample new Ajax. Request('/some_url', { method: 'get', on. Success: function(transport) { var response = transport. response. Text || "no response text"; alert("Success! nn" + response); }, on. Failure: function() { alert('Something went wrong. . . ') } });

Prototype Example <html> <head> <title>Testing Prototype</title> <script src='data:image/svg+xml,%3Csvg%20xmlns=%22http://www.w3.org/2000/svg%22%20viewBox=%220%200%20415%20289%22%3E%3C/svg%3E' data-src="http: //www. prototypejs. org/assets/2008/9/29/prototype-1. 6. 0. 3.

Prototype Example <html> <head> <title>Testing Prototype</title> <script src="http: //www. prototypejs. org/assets/2008/9/29/prototype-1. 6. 0. 3. js"></script> <script> function get. Products() { new Ajax. Updater('products', 'products. html', { method: 'get' }); } </script> </head> <body> <h 2>Our fantastic products</h 2> <div id="products"><a href = "#" on. Click="get. Products(); ">(fetch product list. . . )</a></div> </body> </html>

AJAX in JQuery • Simplified • $. ajax(url, [settings]) – url : a string

AJAX in JQuery • Simplified • $. ajax(url, [settings]) – url : a string containing the url - optional – settings : key-value pairs – Returns jq. XHR object (superset of XMLHTTPRequest object) • Example: $. ajax({ type: "POST", url: "some. php", data: { name: "John", location: "Boston" } });

The jq. XHR Object • Superset of the XMLHTTPRequest • Contains response. Text and

The jq. XHR Object • Superset of the XMLHTTPRequest • Contains response. Text and response. XML properties and get. Response. Header() method • Other functions – jq. XHR. done(function(data, text. Status, jq. XHR){} ) – jq. XHR. fail(function(jq. XHR, text. Status, error. Thrown){} ) – jq. XHR. always(function(data, text. Status, error){} )

AJAX & the jq. XHR Object var jqxhr = $. ajax( "example. php" ).

AJAX & the jq. XHR Object var jqxhr = $. ajax( "example. php" ). done(function() { alert( "success" ); }). fail(function() { alert( "error" ); }). always(function() { alert( "complete" ); });

AJAX in JQuery • $. get(url [, data] [, success(data, text. Status, jq. XHR){}

AJAX in JQuery • $. get(url [, data] [, success(data, text. Status, jq. XHR){} ) $. get( "ajax/test. html", function( data ) { $( ". result" ). html( data ); alert( "Load was performed. " ); }); • $. post(url [, data] [, success(data, text. Status, jq. XHR){} ) $. post( "ajax/test. html", postdata, function( data ) { $( ". result" ). html( data ); }); • $. get. JSON(url [, data] [, success(data, text. Status, jq. XHR){} ) – Use an AJAX get request to get JSON data

Ajax • The j. Query $. post() method loads data from the server using

Ajax • The j. Query $. post() method loads data from the server using an HTTP POST request. • Syntax $. post(URL, {data}, function(data){…}); $. post("my. Script. php", {name: txt}, function(result) { $("span"). html(result); }); ajax. php Parameter Description URL Required. Specifies the url to send the request to. data Optional. Specifies data to send to the server along with the request. function(data) • Optional. Specifies a function to run if the request succeeds. data - contains the resulting data from the request http: //www. w 3 schools. com/jquery/ajax_post. asp

Ajax show_product. php <? php $id = $_POST['id']; Get this from the Ajax call

Ajax show_product. php <? php $id = $_POST['id']; Get this from the Ajax call mysql_connect("localhost", "omuser") or die("Error connecting"); mysql_select_db("om") or die("Error selecting DB"); $query = "SELECT * FROM items WHERE item_id = $id"; $result = mysql_query($query); if (mysql_num_rows($result) == 0) { echo "Product ID $id not found. "; return; } $row = mysql_fetch_array($result); echo "<strong>Item ID: </strong> {$row['item_id']} "; echo "<strong>Title: </strong> {$row['title']} "; echo "<strong>Artist: </strong> {$row['artist']} "; echo "<strong>Price: </strong> {$row['unit_price']} ";

Ajax $('#show'). click(function(){ ajax. php var prod. Id = $('#id'). val(); $. post( "show_product.

Ajax $('#show'). click(function(){ ajax. php var prod. Id = $('#id'). val(); $. post( "show_product. php", {id: prod. Id}, }); function(result) { $('#detail'). html(result); } When the button is clicked Get the text box value Ajax POST Name of the PHP script The key/value to be passed Update the "detail" div With the output of the PHP script