Presentation is loading. Please wait.

Presentation is loading. Please wait.

11 Ajax JavaScript & jQuery the missing manual Chapter 11.

Similar presentations


Presentation on theme: "11 Ajax JavaScript & jQuery the missing manual Chapter 11."— Presentation transcript:

1 11 Ajax JavaScript & jQuery the missing manual Chapter 11

2 22 Objectives You will be able to Write JavaScript code that communicates with the server without doing a postback. Use jQuery functions to perform asynchronous communication between JavaScript code in the browser and C# code in the server.

3 33 Ajax Asynchronous JavaScript and XML Not a product or a technology. A catchy name for a way to improve the user experience by reducing delays due to postbacks and page replacments. Consider google maps.

4 44 Ajax Name coined by Jesse James Garrett in an online article Feb. 18, 2005: http://www.adaptivepath.com/ideas/ajax-new-approach-web-applications/ Ajax technologies JavaScript XMLHttpRequest DOM CSS XML, JSON Don’t confuse “Ajax” with Microsoft’s Ajax enabled components.

5 55 Using XMLHttpRequest The JavaScript object XMLHttpRequest supports asynchronous communication with the server. Send a Get or Post message to the server. Don’t wait for a response. Continue script operation. JavaScript event fires when response is received from the server. Event handler invokes a JavaScript callback function. Callback function updates the page by modifying the DOM

6 66 Using XMLHttpRequest Has no necessary connection with XML. JSON is favored by many JavaScript programmers. JavaScript Object Notation Get a text message back from the server. Can be XML, JSON, or anything else. Client and server have to agree on how to interpret the message. If the message is XML or JSON we have good support for parsing and using it in both the DOM API and jQuery.

7 77 Using XMLHttpRequest The bad news: Creating an XMLHttpRequest object is browser dependent. Three different ways to create the object depending on which browser is running the script. The good news: jQuery hides the browser differences.

8 88 How to Use XMLHttpRequest Create an XMLHttpRequest object. Specify a URL and method (Get/Post) Send the request. Server handles request Sends response Handle response event. jQuery make this easy. Hides most of the complexity. http://api.jquery.com/category/ajax/

9 9 Simplest Ajax Demo Just load an HTML file into the current page without doing a postback. The "Hello, World!" of Ajax

10 10 Using Ajax with jQuery Create a new C# ASP.NET empty web site. Ajax_jQuery_Demo Add New Item: HTML Page Default.html Download jQuery http://jquery.com/download/ Add to website. Add New Item: JavaScript File Ajax_jQuery_Demo.js

11 11 Default.html

12 12 File to Load Add a new HTML page to the website hello.html This is the file that we will add to the page asynchronously. Delete all of the initial boilerplate provided by Visual Studio Add a single tag

13 13 hello.html

14 14 Loading HTML Asynchronously The jQuery function load Requests a specified URL from the server. Appends the HTML to the selected object. JavaScript & jQuery the missing manual, pages 349-356 http://api.jquery.com/load/

15 15 Loading HTML Asynchronously The jQuery function load We will need a element with ID of Message.

16 16 Default.aspx We need to call Load_HTML in response to a user click. Add some text and a button to Default.aspx as shown on the next slide. Note that we do not want a postback when the button is clicked. input type will be button, not submit. Just call Load_HTML when the button is clicked.

17 Default.html Click this button to retrieve an HTML file from the server without a postback. 17 Try it!

18 18 The App Started

19 19 Load Done End of Section

20 20 Retrieving Dynamic Content Normally we will not want to retrieve a file from the server. Typically we want something computed by server code. Let’s change our script to get content supplied by code running on the server. First just static text. Then result of a computation. Add a new web form to the web site ajax_responder.aspx

21 21 ajax_responder.aspx Delete everything from ajax_responder.aspx except the Page directive. The response will consist of output from server side code.

22 22 ajax_responder.aspx.cs

23 23 The jQuery Get Method We will use the jQuery get() method to retrieve data from the server asynchronously. Without a postback. Uses the JavaScript XMLHttpRequest Hides browser differences. Hides differences between get and post. JavaScript & jQuery the missing manual, pages 356-358, 365-370 http://api.jquery.com/jQuery.get/

24 24 The jQuery Get Method $.get(url, data, callback) url Page to request Must be a page on the same server data Query string or JavaScript object literal to send to server callback JavaScript function to process result on the browser Note that there is no jQuery selector $ stands alone

25 25 The Callback Function Takes two parameters, both strings data Whatever the server sent as its response status 'success' or error message

26 26 The jQuery text() Method We will use the jQuery text() method to update the page. The jQuery text() method, called with a string argument, replaces the text of the selected element with the argument.

27 27 Ajax_Query_Demo.js

28 28 Update Default.html Try it!

29 29 Initial Screen Click the button.

30 30 After Click End of Section

31 31 Sending Data to the Server Usually we will send some information to the server on an Ajax request. Used by the server in processing the request.

32 32 Passing Request Info to the Server To pass request information to the server in a GET, put it into a query string. Set the query string in the second argument to $.get() Let’s modify the Ajax demo to get the server to add two numbers input by the user. Modify Default.html. Add two input textboxes Add a new function to Ajax_jQuery_Demo.js Compute_Sum() Add a new ASPX page to handle the Ajax request. Server_Calculation.aspx Details on following slides.

33 33 Reality Check Keep in mind that this is a very simple example, to illustrate the mechanism. Not realistic! In the real world, functions invoked by Ajax calls need to do a lot of work in order to justify the message cost. Work that is not practical to do on the browser in JavaScript. For example, database queries.

34 34 Default.html We have removed the onclick attribute from the button.

35 Default.html 35 We have removed onclick from the button.

36 36 “The jQuery Way” Ajax_jQuery_Demo.js $(document).ready( function() { $('#btnComputeSum').bind('click', Compute_Sum); }); This anonymous function will be executed when the page has been loaded on the browser. The “ bind ” says to execute the JavaScript function Compute_Sum when btnComputeSum is clicked. The Compute_Sum function will receive a jQuery Event object as input parameter. See “Unobtrusive JavaScript” http://en.wikipedia.org/wiki/Unobtrusive_JavaScript

37 37 function Compute_Sum(evt) { $.get('Server_Calculation.aspx', 'input1=' + $('#Text1').val() + '&input2=' + $('#Text2').val(), Process_Response); } Browser will request Server_Calculation.aspx using the get method. Second argument is the query string Built using contents of the two TextBoxes Example: input1=3&input2=4 Third argument is the callback function to be executed when the result is received from the browser. “The jQuery Way” URL Query String Callback Function Add to Ajax_jQuery_Demo.js

38 38 The Callback Function function Process_Response(result, status) { if (status=='success') { $('#Message').text(result); } else { $('#Message').text('ERROR ' + result); } result is whatever the server code sends. If calculation is successful, the calculation result. If error, an error message.

39 In Ajax_jQuery_Demo.js $(document).ready(function () { $('#btnComputeSum').bind('click', Compute_Sum); }); function Compute_Sum(evt) { $.get('Server_Calculation.aspx', 'input1=' + $('#Text1').val() + '&input2=' + $('#Text2').val(), Process_Response); } function Process_Response(result, status) { if (status == 'success') { $('#Message').text(result); } else { $('#Message').text('Error retrieving data from server'); } 39

40 40 Server Code JavaScript for the browser is complete. Now we need to write the code that will run on the server. Add a new Web Form to handle the Ajax request. Server_Calculation.aspx Delete the boilerplate in the.aspx file. Everything except the Page directive.

41 41 Server_Calculation.aspx

42 Server_Calculation.aspx.cs using System; public partial class Server_Calculation : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { string input1 = Request.QueryString["input1"]; string input2 = Request.QueryString["input2"]; Decimal augend = 0.00M; Decimal addend = 0.00M; if (Decimal.TryParse(input1, out augend)) { if (Decimal.TryParse(input2, out addend)) { Decimal sum = augend + addend; Response.Write(sum.ToString()); } else { Response.Write("Second input is not a valid numeric value"); } else { Response.Write("First input is not a valid numeric value"); } Try it!

43 43 Ajax Calculation in Action

44 44 Invalid Input

45 Another Invalid Input 45 Whoa!! What’s going on here?

46 Why is input of “12%33” accepted as valid? Set a breakpoint in Server_Calculation 46

47 In Server_Calculation 47 What we got for Request.QueryString on the server.

48 In Ajax_jQuery_Demo.js 48 This is executed on the browser.

49 In Ajax_jQuery_Demo.js 49 On the browser The browser sent %33 in the query string. You can verify this with Fiddler.

50 What’s going on here? The query string in the URL was input1=12%33&input2=123 The string returned by ASP.NET as the QueryString property of Request was input1=123&input2=123 Why? 50

51 What’s going on here? The received query string was URL Decoded. http://msdn.microsoft.com/en-us/library/6196h3wt%28v=vs.110%29.aspx The query string was URL Encoded before being sent to the server in a GET request. The server URL Decodes the string to get back the original string. But in this case it doesn’t! URLDecode is not an exact inverse of URLEncode. 51 End of Section

52 52 References Documentation for the jQuery methods that we have used can be found in JavaScript & jQuery the missing manual and on the jQuery web site. bind pages 177-179 http://api.jquery.com/bind/ load page 349 http://api.jquery.com/load/ get pages 356-358 http://api.jquery.com/jQuery.get/ text page 139 http://api.jquery.com/text/#text2


Download ppt "11 Ajax JavaScript & jQuery the missing manual Chapter 11."

Similar presentations


Ads by Google