Ajax has always been a very interesting technology on the web and there are many libraries that can be used to perform Ajax requests. In this article we will learn how to perform Ajax requests using the JQuery library.
Introduction:
Ajax has always been a very interesting technology on the web and there are many libraries that can be used to perform Ajax requests. In this article we will learn how to perform Ajax requests using the JQuery library.
Why JQuery?
JQuery not only provides extensive JavaScript support but also provides very powerful Ajax API. JQuery also supports plug-ines like JQuery UI. You can find an example of JQuery UI using the link below:
Drag and Drop with Persistence Using JQuery
Making a Simple JQuery Request:
Let’s start by making a simple JQuery Ajax request in which we will read the contents of a text file and display it on the screen. It is assumed that you have already downloaded the JQuery library from the JQuery website and added a reference to it in your code. Let’s create a simple DIV control which will be used to display the contents of the requested text file.
<div id="responseDiv"></div>
</div>
And here is the associated JQuery code:
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$("#responseDiv").load("SomeTextFile.txt");
})
</script>
In the code above we are attaching the ready event to the document which will be fired once the DOM is loaded. The “responseDiv” is the id of the DIV control. The load function will make an Ajax request to the “SomeTextFile.txt” file and display the contents of the file in the DIV control.
That was a very simple Ajax request. Let’s see how we can send parameters to a server using the JQuery Ajax framework.
Sending Parameters Using JQuery Ajax:
In this example we are going to send some parameters to the server using the JQuery Ajax library. Check out the following code:
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$.post("SomePage.aspx",{ text : 'hello world' });
})
</script>
The $.post method is used to send the values to the server. There is also a $.get method which is used to retrieve the data from the server. The $.post method contains two arguments. The first one is the URL of the resource and the second one is the variable that you need to send. The URL name in our case is a page named “SomePage.aspx” and the variable name is “text” whose value is “hello world”.
Now, let’s see the code in SomePage.aspx page which is used to access the variable and its value.
public partial class SomePage : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Form["text"] == null) return;
string text = Request.Form["text"] as String;
}
}
The variable “text” becomes part of the Request.Form collection and we can access it using the key. The line Request.Form[“text”] will retrieve the value of the “text” key which is “hello world” and assign it to the string variable text.
This is nice but usually you won’t be making calls to the ASPX pages. Let’s see how we can send parameters to the web service and get a result back from it.
Invoking Web Service Methods Using JQuery Ajax:
We have added a simple web service named “SimpleService.asmx”. We are going to invoke the default “HelloWorld” method using the JQuery Ajax library. Take a look at the HelloWorld webmethod below:
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
In order to invoke the HelloWorld method of the SimpleService we need to find out the URL for the method. You can easily find out the URL by running the service and looking at the HTTP POST section which will appear after you click on the WebMethod. The URL for the above service is shown below:
/SimpleService.asmx/HelloWorld
Now, let’s make an Ajax request to the above method:
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$.post("SimpleService.asmx/HelloWorld",helloworld_callback);
})
function helloworld_callback(response)
{
alert(response.text);
}
</script>
In the above code we are making a POST request to the web service method “HelloWorld” and handling the response in the helloworld_callback function. The response object will be of type XMLDOMDocument and the “text” property will contains our result, “Hello World”.
Let’s make things a little more practical! We will send a parameter to a web method and get a response in the JSON format. The JSON format will allow us to easily navigate the properties of the object.
For this demo we will use the Customer entity class which is implemented as shown below:
public class Customer
{
private string _firstName;
private string _lastName;
public string FirstName
{
get { return _firstName; }
set { _firstName = value; }
}
public string LastName
{
get { return _lastName; }
set { _lastName = value; }
}
}
Nothing fancy! Now, let’s take a look at the GetCustomer web method.
[WebMethod]
public string GetCustomer(int id)
{
Customer customer = new Customer() { FirstName = "Mohammad", LastName = "Azam" };
JavaScriptSerializer s = new JavaScriptSerializer();
return s.Serialize(customer);
}
The GetCustomer method takes a parameter named “id” (We don’t actually do anything with the parameter. It is just for the sake of this demo). A Customer object is constructed and serialized as JSON string using the JavaScriptSerializer class (This class has been marked obsolete. Please take a look at the System.Runtime.Serialization.DataContractJsonSerializer class) and returned to the caller.
Now, you can access the Customer object from the client side using the following code:
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$.post("SimpleService.asmx/GetCustomer",{ id : '23' },helloworld_callback);
})
function helloworld_callback(response)
{
var customer = eval("(" + response.text + ")");
alert(customer.FirstName);
}
</script>
This is much better approach since now we don’t have to iterate through the XMLDOMDocument object to get the property names and values.
Conclusion:
JQuery Ajax support is as slick as the JQuery JavaScript library. It allows the developer to write less code and achieve more.
Happy programming!