Top Banner
1 1 Ajax JavaScript & jQuery the missing manual Chapter 11
49
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

11

Ajax

JavaScript & jQuery the missing manual

Chapter 11

Page 2: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

2 2

Objective

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.

Page 3: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

3 3

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.

Page 4: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

4 4

Ajax

Name coined by Jesse James Garrett in an online article Feb. 18, 2005:http://www.adaptivepath.com/ideas/essays/archives/000385.php

Ajax technologies JavaScript

XMLHttpRequest CSS XML

Don’t confuse “Ajax” with Microsoft’s Ajax enabled components.

Page 5: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

5 5

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

Page 6: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

6 6

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.

Page 7: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

7 7

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.

Page 8: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

8 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. http://api.jquery.com/category/ajax/

Page 9: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

9

Simplest Ajax Demo

Just load an HTML file into the current page without doing a postback.

Page 10: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

10 10

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 http://docs.jquery.com/Downloading_jQuery#Download_jQuery

Add to website.

Add New Item: JScript File Ajax_jQuery_Demo.js

Page 11: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

11

Default.aspx

Page 12: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

12

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

Page 13: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

13

hello.html

Page 14: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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/

Page 15: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

15

Loading HTML Asynchronously

The jQuery function load

We will need a <div> element with ID of Message.

Page 16: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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.

Page 17: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

17

Default.aspx

Try it!

Page 18: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

18

The App Started

Page 19: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

19

Load Done

End of Section

Page 20: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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

Page 21: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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.

Page 22: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

22 22

ajax_responder.aspx.cs

Page 23: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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/

Page 24: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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 Function to process result

Note that there is no jQuery selector $ stands alone

Page 25: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

25

The Callback Function

Takes two parameters, both strings data

Whatever the server sent as its response status

'success' or error message

Page 26: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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.

Page 27: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

27

Ajax_Query_Demo.js

Page 28: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

28

Update Default.aspx

Try it!

Page 29: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

29

Initial Screen

Page 30: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

30

After Click

Page 31: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

31

Chrome

Page 32: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

32

Firefox

Page 33: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

33

Safari

End of Section

Page 34: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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.

Page 35: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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

Page 36: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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.

Page 37: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

37

Ajax_Calculation.aspx

ASPX Controls

btnComputeSum

TextBox2TextBox1

Page 38: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

38

Source View

Page 39: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

39

Ajax_Calculation.aspx.cs

The code behind has nothing to do.

Set breakpoint. (Should not be hit.)

Page 40: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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.

Page 41: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

41

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.

“The jQuery Way”

URL

Query String

Callback Function

Page 42: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

42

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

Page 43: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

43

The jQuery Functions

Page 44: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

44

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.

Page 45: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

45

Server_Calculation.aspx

Page 46: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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!

Page 47: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

47

Ajax Calculation in Action

Page 48: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

48

Invalid Input

Page 49: 11 Ajax JavaScript & jQuery the missing manual Chapter 11.

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

preventDefault pages 175, 237-238 http://api.jquery.com/event.preventDefault/