AJAX Using Jquery and ASP
AJAX Using Jquery and ASP
NET
by Farooq Kaiser 7. February 2009 04:14
jQuery is a lightweight JavaScript library and can be downloaded from http://www.jquery.com.
I’ll show you how to use jQuery to call a page method without using the ScriptManager.
This will be our page method in ASP.NET code behind.
public partial class _Default : Page
{
[WebMethod]
public static string GetData()
{
return String.Format("Sever time is..{0}", DateTime.Now.ToString());
}
}
Here is our Default.aspx
<html>
<head>
<title>Demo with jQuery</title>
<script type="text/javascript" src="jquery-1.2.6.min.js"></script>
<script type="text/javascript" src="Demo.js"></script>
</head>
<body>
<div id="divResult">Click here to get server time</div>
</body>
</html>
You can increase the performance by replacing above Script with google AJAX Libraries.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.j
s"></script>
Google AJAX Libraries can be found here http://code.google.com/apis/ajaxlibs/
Here is our Demo.js
$(document).ready(function() {
$("#divResult").click(function() {
$.ajax({
type: "POST",
url: "Default.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
$("#divResult").text(res.d);
}
});
});
});
Jquery is a very powerful tool that extends the javascript library, and there are quite a few
methods with in jquery that makes it much easier to work with ajax. Lets take a look at an
example.
Here is the html code to get a Parcel page shipping date. Note this can be easily
modified to call any asp.net code behind function or method from jQuery.
<html>
<head>
<title>Call Page Method with Jquery Ajax</title>
<script type="text/javascript" src="jquery.js"></script>
//add the below jquery code here
</head>
<body>
<div id="Result">
<input type="text" id="txtTrackingNumber" />
<input type="button" id="btnSubmit" value="Search Parcel" />
<div id="ParcelShippingDate"></div>
</div>
</body>
</html>
type: "POST",
url: "testSearch.aspx/GetMyShippingDate",
contentType: "application/json; charset=utf-8",
data: "{'tracking_num': '" + $
("#txtTrackingNumber").val() + "'}",
dataType: "json",
success: function (date) {
},
error: Failed
});
});
});
function Success(result) {
$("#ParcelShippingDate").html(result.d);
}
function Failed(result) {
alert(result.status + " " + result.statusText);
}
</script>
}
else
{
return "TrackingNumber " + tracking_num + " will be
delivered on 12/25/2025";
}
}
http://webdeveloperpost.com/Articles/How-to-use-jquery-ajax-in-asp-dot-
net-web-page.aspx
http://www.fairnet.com/Blog/post/AJAX-using-jquery-and-ASPNET.aspx
http://weblogs.asp.net/craigshoemaker/archive/2008/11/07/using-jquery-
to-call-asp-net-ajax-page-methods-by-example.aspx