jQuery Ajax - University of South Florida

Download Report

Transcript jQuery Ajax - University of South Florida

Ajax
JavaScript & jQuery the missing manual
Chapter 11
1
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.
2
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
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.
4
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
Using XMLHttpRequest

Has no necessary connection with XML.

JSON is favored by many JavaScript programmers.


Get a text message back from the server.



JavaScript Object Notation
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
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.
7
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/
8
Simplest Ajax Demo

Just load an HTML file into the current
page without doing a postback.
9
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
10
Default.aspx
11
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
12
hello.html
13
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/
14
Loading HTML Asynchronously

The jQuery function load
We will need a <div> element with ID of Message.
15
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.
16
Default.aspx
Try it!
17
The App Started
18
Load Done
End of Section
19
Retrieving Dynamic Content

Normally we will not want to retrieve a
file from the server.


Let’s change our script to get content
supplied by code running on the server.



Typically we want something computed by server code.
First just static text.
Then result of a computation.
Add a new web form to the web site

ajax_responder.aspx
20
ajax_responder.aspx

Delete everything from ajax_responder.aspx
except the Page directive .

The response will consist of output from server side code.
21
ajax_responder.aspx.cs
22
The jQuery Get Method

We will use the jQuery get() method to retrieve
data from the server asynchronously.


Uses the JavaScript XMLHttpRequest




Without a postback.
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/
23
The jQuery Get Method
$.get(url, data, callback)

url



data


Query string or JavaScript object literal to send to server
callback


Page to request
Must be a page on the same server
Function to process result
Note that there is no jQuery selector

$ stands alone
24
The Callback Function

Takes two parameters, both strings

data


Whatever the server sent as its response
status

'success' or error message
25
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.
26
Ajax_Query_Demo.js
27
Update Default.aspx
Try it!
28
Initial Screen
29
After Click
30
Chrome
31
Firefox
32
Safari
End of Section
33
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.
34
Passing Request Info to the Server

To pass request information to the server in a GET, put
it into a query string.



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


Use the query string in the second argument to $.get()
Compute_Sum()
Add a new ASPX page to handle the Ajax request.
 Server_Calculation.aspx
Details on following slides.
35
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.

36
Ajax_Calculation.aspx
ASPX
Controls
TextBox1
TextBox2
btnComputeSum
37
Source View
38
Ajax_Calculation.aspx.cs
The code behind has nothing to do.
Set breakpoint. (Should not be hit.)
39
“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.
40
“The jQuery Way”
function Compute_Sum(evt) {
$.get('Server_Calculation.aspx',
URL
'input1=' + $('#TextBox1').val() +
'&input2=' + $('#TextBox2').val(),
Process_Result);
Callback Function
evt.preventDefault();
}


Browser will request Server_Calculation.aspx using the
get method.
Second argument is the query string




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.
41
“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.
42
The jQuery Functions
43
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.
44
Server_Calculation.aspx
45
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!
Ajax Calculation in Action
47
Invalid Input
48
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


load page 349


http://api.jquery.com/jQuery.get/
text page 139


http://api.jquery.com/load/
get pages 356-358


http://api.jquery.com/bind/
http://api.jquery.com/text/#text2
preventDefault pages 175, 237-238

http://api.jquery.com/event.preventDefault/
49