Ajax
Contents 1. Overview of Ajax 2. Using Ajax directly 3. jquery and Ajax 4. Consuming RESTful services Demos folder: Demos\14-Ajax 2
1. Overview of Ajax What is Ajax? Traditional Web applications Ajax Web applications Uses of Ajax Advantages of Ajax 3
What is Ajax? Ajax = "Asynchronous JavaScript with XML" Ajax is a collection of technologies HTML and Cascading Style Sheets (CSS) Web presentation Document Object Model (DOM) and JavaScript Client-side dynamic behaviour XML and XSLT Data exchange, transformation, and manipulation XMLHttpRequest A JavaScript object that performs asynchronous data retrieval Available on most mainstream browsers JavaScript Object Notation (JSON) String representation of an object, easy to handle in client-side JavaScript code 4
Traditional Web Applications HTTP request Browser UI Web server HTTP response HTML and CSS data Client Server(s) 5
Ajax Web Applications JavaScript HTTP request Browser UI Ajax engine Web server HTML and CSS data HTTP response E.g. XML or JSON Client Server(s) 6
Uses of Ajax Some benefits of Ajax: Validate data in real time Auto-complete data entry Load data in the background Refresh data asynchronously Portlets 7
Advantages of Ajax Bandwidth usage Ajax web pages load relatively quickly, because they generate HTML locally within the browser Improved user interface Ajax pages feel more like a standalone app than a Web page Separation of data representation vs. presentation Separate the data from the formatting and styling 8
2. Using Ajax Directly Sample application scenario Defining the Web page UI Creating an XMLHttpRequest object Making asynchronous calls Implementing the server functionality Implementing the call-back function 9
Sample Application Scenario Let's see how to implement a simple Ajax Web app... HTML form at the client Web Server UI components 1 JavaScript UI event handlers 2 RESTful Web service generates and returns XML data 4 JavaScript callback function 3 Example: Open AjaxDemo.sln in Visual Studio 10
Defining the Web Page UI <html> <head> <script type="text/javascript"> See following slide </script> </head> <body> <input type="text" id="myinputfield" onkeyup="myonkeyup()" /> <p id="myechofield" /> </body> </html> /Views/Home/UseAjaxDirectly.cshtml 11
Creating an XMLHttpRequest Object The following JavaScript code creates an XMLHttpRequest object when the HTML page is loaded <script type="text/javascript"> var request = mycreatexmlhttprequest(); function mycreatexmlhttprequest() { try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {} try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {} try { return new XMLHttpRequest(); } catch (e) {} return null; } </script> /Views/Home/UseAjaxDirectly.cshtml 12
Making Asynchronous Calls Here's the myonkeyup() function Passes user's text asynchronously to an ASP.NET MVC Web app At the server, it invokes Echo() on the HomeController class function myonkeyup() { if (request!= null) { var textfield = document.getelementbyid("myinputfield"); var url = "/Home/Echo?text=" + textfield.value; request.open("get", url, true); request.onreadystatechange = myhandlecallback; request.send(null); } } /Views/Home/UseAjaxDirectly.cshtml 13
Implementing the Server Functionality We have implemented the server functionality as an action method in an ASP.NET MVC controller class The method simple returns the same text immediately back to the client (i.e. "echo" ) public class HomeController : Controller { public string Echo(string text) { return text; } } /Controllers/HomeController.cs 14
Implementing the Call-Back Function Here's the client-side JavaScript call-back function Retrieves the response from the server, and updates the UI Note: To retrieve a text response, use the responsetext property To retrieve an XML response, use the responsexml property function myhandlecallback() { if (request.readystate == 4 && request.status == 200) { var outputfield = document.getelementbyid("myechofield"); outputfield.innerhtml = request.responsetext; } } /Views/Home/UseAjaxDirectly.cshtml 15
3. jquery and Ajax Making an Ajax request using Ajax Additional possibilities Setting default values for Ajax requests Using deferred syntax 16
Making an Ajax Request using Ajac To make an Ajax HTTP request to a Web server URL: $.get( url, [ data ], or $.post [ success(data, textstatus, jqueryxmlhttprequestobject) ], [ datatype ] ) 17
Setting Default Values for Ajax Requests You might find that a lot of your Ajax requests require the same parameter settings E.g. cache, datatype, etc. You can use $.ajaxsetup() to set default options for all subsequent Ajax requests E.g. disable caching E.g. specify you want all data to be returned as JSON $.ajaxsetup({ cache: false, datatype: "json" }); 18
Additional Possibilities Generalized Ajax call: $.ajax({ type: "GET", url: "url", data: somedata, success: callback, error: callback }); Example: See UseAjaxWithJQuery.cshtml 19
Using Deferred Syntax jquery also supports a "deferred" syntax as follows: $.ajax({ type: "GET", url: "url", cache: false, data: somedata }).done(function(data) { // success code }).fail(function (data) { // error code }).always(function (data) { // unconditional code }); Example: See UseAjaxWithJQueryDeferred.cshtml 20
Lab A Using Ajax with jquery Lab doc: 14a Using Ajax with jquery.docx Lab exercises: 1. Understanding the application structure 2. Making an Ajax call 3. Processing the Ajax response 4. Additional suggestions 21
4. Consuming RESTful Services The name "REST" What is a RESTful service? HTTP verbs HTTP response codes Example scenario Calling RESTful services using jquery 22
The Name "REST" The name Representational State Transfer is intended to evoke an image of how a well-designed Web application behaves: a network of Web pages forms a virtual state machine, allowing a user to progress through the application by selecting a link or submitting a short data-entry form, with each action resulting in a transition to the next state of the application by transferring a representation of that state to the user. Fielding & Taylor 2002 23
What is a RESTful Service? RESTful services are resource-centric services Endpoints (URIs) represent resources Endpoints are accessible via standard HTTP Endpoints can be represented in a variety of formats (e.g. XML, JSON, HTML, plain text) 24
HTTP Verbs RESTful services use HTTP verbs to define CRUD-style operations on resources HTTP verb POST GET PUT DELETE Meaning in CRUD terms Create a new resource from the request data Read a resource Update a resource from the request data Delete a resource 25
HTTP Response Codes RESTful services return data, and set a response code to indicate the outcome HTTP response code Official HTTP meaning RESTful meaning 200 OK Request OK 201 Created New resource created OK 400 Bad request 403 Forbidden 404 Not found 405 Method not allowed 410 Resource gone 415 Unsupported media type Request malformed Request refused Resource not found Method not supported Can't update or delete item Content type not recognized 500 Internal server error Request processing failed 26
Example Scenario: Overview The easiest way to understand RESTful services is through an example... Imagine a hypothetical company that sells many different parts to many customers The company wants to provide the following Web services: Get list of parts Get detailed part information Submit purchase orders (PO) 27
Example Scenario: Getting a Part List The list of parts available from the company is a resource: A resource is identified via a URI Resource representations are available via HTTP GET E.g. GET http://www.acme.com/parts HTTP/1.1 Gets a representation of the "list of parts" resource <?xml version="1.0"?> <p:parts xmlns:p="http://www.acme.com" xmlns:xl="http://www.w3.org/1999/xlink"> <Part id="0345" xl:href="http://www.acme.com/parts/0345"/> <Part id="0346" xl:href="http://www.acme.com/parts/0346"/> <Part id="0347" xl:href="http://www.acme.com/parts/0347"/> <Part id="0348" xl:href="http://www.acme.com/parts/0348"/> </p:parts> A representation typically contains links to other resources 28
Example Scenario: Getting Part Info Detailed part info is also a resource identified with a URL Getting detailed information: E.g. GET http://www.acme.com/parts/0346 HTTP/1.1 Gets a representation of a specific part <?xml version="1.0"?> <p:part xmlns:p="http://www.acme.com" xmlns:xl="http://www.w3.org/1999/xlink"> <Part-ID>0346</Part-ID> <Name>Widget-A</Name> <Desc>This part is used in the pilot's cabin</desc> <Spec xl:href="http://www.acme.com/parts/0346/spec"/> <UnitCost currency="usd">0.10</unitcost> </p:part> How the representation is generated is unspecified Note: the URIs are logical URIs, not necessarily static pages 29
Example Scenario: Submitting a PO To order a part, the client submits a purchase order (PO) The PO is an XML document The PO is submitted using standard HTTP POST <?xml version="1.0"?> <p:order xmlns:p="http://www.acme.com" xmlns:xl="http://www.w3.org/1999/xlink"> <Part xl:href="http://www.acme.com/parts/0346"/> <Quantity>10</Quantity> <Date>2014-09-01</Date>... </p:order> A PO is shared information between the company and client The Web service returns a URI for the submitted PO The client may delete the PO using HTTP DELETE 30
Calling RESTful services using jquery (1 of 4) To issue a GET request: $.ajax({ type: "GET", url: urlofitemtoget, cache: false, accepts: { json: 'application/json' }, success: function(data) { }, error: }); function(xhr, message) { } 31
Calling RESTful services using jquery (2 of 4) To issue a POST request: $.ajax({ type: url: cache: "POST", aurl, false, contenttype: "application/json", data: JSON.stringify(anObject), success: function(data) { }, error: }); function(xhr, message) { } 32
Calling RESTful services using jquery (3 of 4) To issue a PUT request: $.ajax({ type: url: cache: "PUT", aurl, false, contenttype: "application/json", data: JSON.stringify(anObject), success: function() { }, error: }); function(xhr, message) { } 33
Calling RESTful services using jquery (4 of 4) To issue a DELETE request: $.ajax({ type: url: cache: "DELETE", urlofitemtodelete, false, success: function() { }, error: }); function(xhr, message) { } 34
Lab B Consuming RESTful Services Lab doc: 14b Consuming RESTful Services using jquery and Ajax.docx Lab exercises: 1. Familiarization with the server-side code 2. Familiarization with the client-side code 3. Inserting a product 4. Updating a product 5. Deleting a product 6. Additional suggestions 35
Any Questions? 36