AJAX Asynchronous Javascript And XML. AJAX A lot of hype –It has been around for a while –Not complex Powerful approach to building websites –Think differently.

Slides:



Advertisements
Similar presentations
JQUERY/AJAX ALIREZA KHATAMIAN DELARAM YAZDANSEPAS.
Advertisements

9. AJAX & RIA. 2 Motto: O! call back yesterday, bid time return. — William Shakespeare.
Asynchronous HTTP request generation in JavaScript (AJAX)
19-Jun-15 Ajax. The hype Ajax (sometimes capitalized as AJAX) stands for Asynchronous JavaScript And XML Ajax is a technique for creating “better, faster,
AJAX asynchronous server-client communication. Test.
Chapter 6 DOJO TOOLKITS. Objectives Discuss XML DOM Discuss JSON Discuss Ajax Response in XML, HTML, JSON, and Other Data Type.
Agenda What is AJAX? What is jQuery? Demonstration/Tutorial Resources Q&A.
The Document Object Model (DOM) & Asynchronous Javascript And XML (AJAX) : an introduction UFCEKG-20-2 : Data, Schemas and Applications.
Internet Applications Spring Review Last week –MySQL –Questions?
User Interface Design using jQuery Mobile CIS 136 Building Mobile Apps 1.
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.
CGI and AJAX CS-260 Dick Steflik.
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
Databases.  Multi-table queries  Join ▪ An SQL JOIN clause is used to combine rows from two or more tables, based on a common field between them. 
CSCI 6962: Server-side Design and Programming Introduction to AJAX.
Lecture 12 – AJAX SFDV3011 – Advanced Web Development Reference: 1.
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.
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.
AJAX (also known as: XMLHTTP, Remote Scripting, XMLHttpRequest, etc.) Matt Warden.
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.
AJAX Compiled from “AJAX Programming” [Sang Shin] (Asynchronous JavaScript and XML)
Asynchronous Javascript And XML AJAX : an introduction UFCEUS-20-2 : Web Programming.
CISC 3140 (CIS 20.2) Design & Implementation of Software Application II Instructor : M. Meyer Address: Course Page:
JQuery JavaScript is a powerful language but it is not always easy to work with. jQuery is a JavaScript library that helps with: – HTML document traversal.
AJAX Asynchronous JavaScript & XML A short introduction.
SYST Web Technologies SYST Web Technologies AJAX.
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.
SE-2840 Dr. Mark L. Hornick 1 Introduction to Ajax Asynchronous Javascript And XML.
CHAPTER 8 AJAX & JSON WHAT IS AJAX? Ajax lets you…
AJAX and REST. Slide 2 What is AJAX? It’s an acronym for Asynchronous JavaScript and XML Although requests need not be asynchronous It’s not really a.
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)‏
Javascript AJAX HTML WEB SERVER Asynchronous. Javascript HTML events DOM – document object model browser internal view of html page compute.
JavaScript, Sixth Edition Chapter 11 Updating Web Pages with Ajax.
JavaScript and Ajax Week 10 Web site:
JQuery form submission CIS 136 Building Mobile Apps 1.
NCCUCS 軟體工程概論 Lecture 5: Ajax, Mashups April 29, 2014.
How to consume a RESTful service using jQuery. Introduction  In this post we see how to consume the RESTful service described in the post Design a RESTful.
JQuery, JSON, AJAX. AJAX: Async JavaScript & XML In traditional Web coding, to get information from a database or a file on the server –make an HTML form.
Mobile Web Design Best Practices Three Approaches to Mobile Web: ◦ Develop a new mobile site with a.mobi TLD ◦ Create a separate website hosted within.
AJAX. Objectives Understand and apply AJAX Using AJAX in DOJO library.
CSE 154 Lecture 11: AJAx.
Not a Language but a series of techniques
AJAX AJAX = Asynchronous JavaScript and XML.
AJAX and REST.
XMLHttp Object.
Introduction to jQuery
Web System & Technology
CSE 154 Lecture 11: AJAx.
CSE 154 Lecture 22: AJAX.
AJAX Robin Burke ECT 360.
JavaScript & AJAX.
JavaScript & jQuery AJAX.
Chengyu Sun California State University, Los Angeles
AJAX CS-422 Dick Steflik.
Intro to Ajax Fred Stluka Jan 25, 2006.
Chengyu Sun California State University, Los Angeles
Chengyu Sun California State University, Los Angeles
Presentation transcript:

AJAX Asynchronous Javascript And XML

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, ajax13, etc.

ONE SHAKE PLEASE ONE SHAKE PLEASE

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 XMLHttpRequest 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 XMLHttpRequest Object var request; function createRequest() { try { request = new XMLHttpRequest(); if (request.overrideMimeType) { request.overrideMimeType('text/xml'); } } catch (trymicrosoft) { try { request = new ActiveXObject("Msxml2.XMLHTTP"); } catch (othermicrosoft) { try { request = new ActiveXObject("Microsoft.XMLHTTP"); } catch (failed) { request = false; } if (!request) alert("Error initializing XMLHttpRequest!"); }

Communicating Steps –Gather information (possibly from HTML form) –Set up the URL –Open the connection –Set a callback method –Send the request function getCustomerInfo() { var phone = document.getElementById("phone").value; var url = "/cgi-local/lookupCustomer.php?phone=" + escape(phone); request.open("GET", url, true); request.onreadystatechange = updatePage; request.send(null); }

Handling Server Responses When the server responds, your callback method will be invoked. –It is called at various stages of the process –Test readyState function updatePage() { if (request.readyState == 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() 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 XMLHttpRequest Object Methods –abort() cancel current request –getAllResponseHeaders() Returns the complete set of http headers as a string –getResponseHeader(“headername”) Return the value of the specified header –open(“method”, “URL”, async, “uname”, “passwd”) Sets up the call –setRequestHeader(“label”, “value”) –send(content) Actually sends the request

The XMLHttpRequest Object Properties –onreadystatechange Event handler for an event that fires at every state change –readyState Returns the state of the object –responseText Returns the response as a string –responseXML Returns the response as XML - use W3C DOM methods –status Returns the status as a number - ie. 404 for “Not Found” –statusText Returns the status as a string - ie. “Not Found”

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.readyState == 4 and request.status == 200 –Get the response in either text or xml request.responseText or request.responseXML –Process the response appropriately for viewing –Get the objects on the page that will change document.getElementById or document.getElementByName, etc. –Make the changes

AJAX Response Handler function updatePage() { if (request.readyState == 4) { if (request.status == 200) { var response = request.responseText.split("|"); // “order|address” document.getElementById("order").value = response[0]; document.getElementById("address").innerHTML = response[1]; } else alert("status is " + request.status); }

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.phpajaxform.htmlajax.jsajax.php – 360/simpleajax/ajaxform.htmlhttp://dna.cs.byu.edu/~snell/Classes/CS 360/simpleajax/ajaxform.html

function loadMap(filename) { var request = GXmlHttp.create(); request.open("GET", filename, true); request.onreadystatechange = function() { if (request.readyState == 4) { var xmlDoc = request.responseXML; var markers = xmlDoc.documentElement.getElementsByTagName("marker"); mapmarkers.length=0; for (var i = 0; i < markers.length; i++) { mapmarkers.push(createMarker(new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng"))), markers[i].getAttribute("note"))); map.addOverlay(mapmarkers[i]); } map.setCenter(new GLatLng(parseFloat(markers[0].getAttribute("lat")), parseFloat(markers[0].getAttribute("lng"))), 13); mappoints.length = 0; var trailpoints = xmlDoc.documentElement.getElementsByTagName("point"); for (var i = 0; i < trailpoints.length; i++) { var tpoint = new GLatLng(parseFloat(trailpoints[i].getAttribute("lat")), parseFloat(trailpoints[i].getAttribute("lng"))); mappoints.push(tpoint); } map.addOverlay(new GPolyline(mappoints)); } request.send(null); } // Download the data in data.xml and load it on the map. The format we expect is: //

AJAX Libraries Prototype – Scriptaculous – JQuery – Mochikit –

Prototype Sample new Ajax.Request('/some_url', { method:'get', onSuccess: function(transport) { var response = transport.responseText || "no response text"; alert("Success! \n\n" + response); }, onFailure: function() { alert('Something went wrong...') } });

Prototype Example Testing Prototype function getProducts() { new Ajax.Updater('products', 'products.html', { method: 'get' }); } Our fantastic products (fetch product list...)

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

The jqXHR Object Superset of the XMLHTTPRequest Contains responseText and responseXML properties and getResponseHeader() method Other functions –jqXHR.done(function(data,textStatus, jqXHR){} ) –jqXHR.fail(function(jqXHR, textStatus, errorThrown){} ) –jqXHR.always(function(data, textStatus, error){} )

AJAX & the jqXHR 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,textStatus, jqXHR){} ) $.post(url [, data] [, success(data,textStatus, jqXHR){} ) $.getJSON(url [, data] [, success(data,textStatus, jqXHR){} ) –Use an AJAX get request to get JSON data $.get( "ajax/test.html", function( data ) { $( ".result" ).html( data ); alert( "Load was performed." ); }); $.post( "ajax/test.html", postdata, function( data ) { $( ".result" ).html( data ); });

Ajax The jQuery $.post() method loads data from the server using an HTTP POST request. Syntax $.post(URL, {data}, function(data){…}); $.post("myScript.php", {name:txt}, function(result) { $("span").html(result); }); ajax.php ParameterDescription URLRequired. Specifies the url to send the request to. dataOptional. 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

Ajax <?php $id = $_POST['id']; mysql_connect("localhost", "omuser", "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 " Item ID: {$row['item_id']} "; echo " Title: {$row['title']} "; echo " Artist: {$row['artist']} "; echo " Price: {$row['unit_price']} "; <?php $id = $_POST['id']; mysql_connect("localhost", "omuser", "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 " Item ID: {$row['item_id']} "; echo " Title: {$row['title']} "; echo " Artist: {$row['artist']} "; echo " Price: {$row['unit_price']} "; Get this from the Ajax call show_product.php

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