Using AJAX with ASP
Using AJAX with ASP.NET - Calling ASP.NET Web Service (Part 4)
Introduction
In
Part 2 we discussed how to work with DataSet returned by the web form. The
disadvantage of using web forms as data suppliers is that one web form typically
returns only one DataSet. You need to put all the code in the Page_Load. It
would be much more organized and useful if you can call Web Service using AJAX.
You can then neatly organize your code in various web methods and call the
required one from the JavaScript code. In this article I will illustrate how web
services can be called from client side JavaScript using HTTP POST method.
Simple Example
As an example we will first build a web service called Service1.asmx and add
the following web method to it:
<WebMethod()> _
Public Function GetOrders(ByVal custid As String) As DataSet
Dim ds As New DataSet
Dim da As New SqlDataAdapter
("select orderid from orders where customerid='"
& custid & "'", "data source=.\vsdotnet;
initial catalog=northwind;user id=sa")
da.Fill(ds, "custoemrs")
Return ds
End Function
This web method accepts the Customer ID and returns a DataSet containing the
relevant OrderIDs.
We are going to use the same web form that we created in
Part 2. The web form has a DropDownList and a ListBox. The
DropDownList displays list of all the Customers from Customers table. When user
selects a specific CustomerID we call the web method through AJAX and
populate the ListBox with the DataSet returned.
Below is the client side JavaScript code that you need to place in the <head>
section of the web form:
var obj;
function GetDataViaAJAX()
{
try
{
obj = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
obj = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e1)
{
obj = null;
}
}
if(obj!=null)
{
obj.onreadystatechange = ProcessResponse;
obj.open("POST", "http://localhost/Service1.asmx/GetOrders");
obj.setRequestHeader("Host","localhost");
obj.setRequestHeader("Content-Type",
"application/x-www-form-urlencoded");
obj.setRequestHeader("Content-Length","12");
obj.send("custid=" +
document.getElementById("DropDownList1").value);
}
return false;
}
function ProcessResponse()
{
if(obj.readyState == 4)
{
if(obj.status == 200)
{
var dsRoot=obj.responseXML.documentElement;
var ddlOrders = document.getElementById("ListBox1");
for (var count = ddlOrders.options.length-1; count >-1; count--)
{
ddlOrders.options[count] = null;
}
var orders = dsRoot.getElementsByTagName('orderid');
var text;
var listItem;
for (var count = 0; count < orders.length; count++)
{
text = (orders[count].textContent ||
orders[count].innerText || orders[count].text);
listItem = new Option(text, text, false, false);
ddlOrders.options[ddlOrders.length] = listItem;
}
}
else
{
alert("Error retrieving data!" + obj.status);
}
}
}
function SetValue()
{
var selectedvalue=document.getElementById("ListBox1").value;
document.getElementById("Hidden1").value=selectedvalue;
return true;
}
The above code is almost the same as in
Part 2 except the one marked in bold. Here, we will be sending a POST
request to the web service. You also need to send HTTP headers using
setRequestHeaders() method. We are hardcoding the content length header but you
may calculate it depending on your actual content. This step is necessary while calling a web service
via POST method. Note the URL of the web service. The web method that you want
to call is included after the web service file name. This is how you call a web
method via POST method. When you call a web service using POST method the web
method parameters need to be sent as request body. Hence we created key-value
pair - custid=<selected_cust_id>.
Code Download
The complete source code of above sample is available for download along with
the article. Please see top of the article for download link.
Summary
Using AJAX one can call any web resource including web forms and web
services. Using web forms, though simple, makes your code bit unorganized and
you may end having many web forms supplying data to various AJAX functions. Web
service on the other hand is a nice way to keep all your data supplier functions
together. It also makes maintaining the application easy.