Presentation is loading. Please wait.

Presentation is loading. Please wait.

JavaScript & jQuery the missing manual Chapter 11

Similar presentations


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

1 JavaScript & jQuery the missing manual Chapter 11
Ajax JavaScript & jQuery the missing manual Chapter 11 1

2 You will be able to Objective
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. 2

3 Asynchronous JavaScript and XML Not a product or a technology.
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. Compare google maps to the original version of mapquest. 3

4 Name coined by Jesse James Garrett in an online article Feb. 18, 2005:
Ajax Name coined by Jesse James Garrett in an online article Feb. 18, 2005: Ajax technologies JavaScript XMLHttpRequest CSS XML Don’t confuse “Ajax” with Microsoft’s Ajax enabled components. 4

5 Send a Get or Post message to the server. Don’t wait for a response.
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 5

6 Has no necessary connection with XML.
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. 6

7 The bad news: The good news: Using XMLHttpRequest
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. 7

8 How to Use XMLHttpRequest
Create an XMLHttpRequest object. Specify a URL and method (Get/Post) Send the request. Handle response event. jQuery make this easy. Hides most of the complexity. 8

9 Just load an HTML file into the current page without doing a postback.
Simplest Ajax Demo Just load an HTML file into the current page without doing a postback.

10 Create a new C# ASP.NET empty web site.
Using Ajax with jQuery Create a new C# ASP.NET empty web site. Ajax_jQuery_Demo Add New Item: Web Form Default.aspx Download jQuery Add to website. Add New Item: JScript File Ajax_jQuery_Demo.js 10

11 Default.aspx

12 Add a new HTML file to the website
File to Load Add a new HTML file 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 <h1> tag

13 hello.html

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

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

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. Set a breakpoint on the Page_Load method to verify that there is not postback.

17 Default.aspx Try it!

18 The App Started

19 Load Done End of Section

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 20

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

22 ajax_responder.aspx.cs 22

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 ,

24 $.get(url, data, callback)
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 Function to process result Note that there is no jQuery selector $ stands alone

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

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 Ajax_Query_Demo.js

28 Update Default.aspx Try it!

29 Initial Screen

30 After Click

31 Chrome

32 Firefox

33 Safari End of Section

34 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.

35 Passing Request Info to the Server
To pass request information to the server in a GET, put it into a query string. Use 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. Add a new Web Form. Ajax_Calculation.aspx Set it as the start page. 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. 35

36 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.

37 Ajax_Calculation.aspx ASPX Controls btnComputeSum TextBox2 TextBox1

38 Source View

39 Ajax_Calculation.aspx.cs The code behind has nothing to do.
Set breakpoint. (Should not be hit.)

40 “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 Compute_Sum function when btnComputeSum is clicked. The Compute_Sum function will receive a jQuery Event object as input parameter.

41 “The jQuery Way” function Compute_Sum(evt) { $.get('Server_Calculation.aspx', 'input1=' + $('#TextBox1').val() + '&input2=' + $('#TextBox2').val(), Process_Result); evt.preventDefault(); } 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. preventDefault supresses postback due to click on a submit. Prevent the normal action for the event. URL Query String Callback Function

42 The callback function. “The jQuery Way”
function Process_Result(result, status) { if (status=='success') { $('#Result').text(result); } else $('#Result').text('ERROR ' + result); The callback function. result is whatever the server code sends. If calculation is successful, the calculation result. If error, an error message.

43 The jQuery Functions

44 JavaScript for the browser is complete.
Server Code JavaScript for the browser is complete. Now we need to write the code that will run on the server. Add a new ASPX page to handle the Ajax request. Server_Calculation.aspx Delete the boilerplate in the .aspx file.

45 Server_Calculation.aspx

46 Try it! 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"); Response.Write("First input is not a valid numeric value"); Try it!

47 Ajax Calculation in Action

48 Invalid Input

49 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 load page 349 get pages text page 139 preventDefault pages 175,


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

Similar presentations


Ads by Google