Web Developer Post

Views: 8825 Comments: 0

How to use jquery ajax in asp dot net web page

Wednesday, December 22, 2010
Categories: ASP.NET, Javascript/JQuery

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 a real world example of using jquery ajax with asp.net

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>

 

Here is the jQuery code to make it all work...

<script type="text/javascript">
$(document).ready(function () {

// Add the page method call as an onclick handler for the button.
$("#btnSubmit").click(function () {

//get the string from the textbox
$.ajax({

type: "POST",
url: "testSearch.aspx/GetMyShippingDate",
contentType: "application/json; charset=utf-8",
data: "{'tracking_num': '" + $("#txtTrackingNumber").val() + "'}",
dataType: "json",
success: function (date) {

// Replace the div's content with the page method's return.
Success(date);

},
error: Failed
});
});
});

function Success(result) {
$("#ParcelShippingDate").html(result.d);
}
function Failed(result) {
alert(result.status + " " + result.statusText);
}

</script>

 

Your code behind in asp.net page

[WebMethod]
public static string GetMyShippingDate(string tracking_num)
{
if (tracking_num == "")
{

return "No Parcel Available";

}
else
{
return "TrackingNumber " + tracking_num + " will be delivered on 12/25/2025";
}
}
?

Previous ArticlesAccessing controls in jQuery and their attributes
Ways to fire jQuery and javascript code when the page loadsNext Article


Add New Comment

Name:*
Email:*
Website:
What does three added to five make?:
Comment:*
 

Reader Comments

No comments have been posted.

Most Popular Articles


Recent Articles



© Copyright 2010. WebDeveloperPost.com
Tampa Web Design By Ricketts