Thursday, December 1, 2011
how to call web service from JQuery
Download source
Making ajax calls to an ASP.NET web service using jQuery is too easy. In this post I’ll explain how to do it!
Start by creating a new web project and adding a new ASMX web service:
Open the new web service and uncomment the following line to allow the web service to be called from script.
[System.Web.Script.Services.ScriptService]
The web service should already have a method called HelloWorld; first I will use jQuery to call this method. Create a new page and add a reference to the jQuery library. Add a button and a label to the form; when the button is clicked I will call the web service and display the result in the label. My form looks like this:
<
form
id
=
"form1"
runat
=
"server"
>
<
div
>
<
asp:Button
ID
=
"btnGo"
Text
=
"Go"
OnClientClick
=
"CallService(); return false;"
runat
=
"server"
/>
<
asp:Label
ID
=
"lblResult"
Text
=
" "
Width
=
"100%"
runat
=
"server"
/>
</
div
>
</
form
>
You can see I’ve set the OnClientClick property of the button to call a JavaScript function called CallService which I will implement in a moment. I have set the text of my label to a non breaking space and set the width to 100%. This is because I will add a CSS class to the label while calling my web service to show an ajax loader. Here is the CSS class:
.loading
{
background-image
:
url
(
'ajax-loader.gif'
);
background-repeat
:
no-repeat
;
}
Finally I need to add the jQuery:
<script type=
"text/javascript"
>
function
CallService() {
$(
"#lblResult"
).addClass(
"loading"
);
$.ajax({
type:
"POST"
,
url:
"MyService.asmx/HelloWorld"
,
data:
"{}"
,
contentType:
"application/json; charset=utf-8"
,
dataType:
"json"
,
success: Success,
error: Error
});
}
function
Success(data, status) {
$(
"#lblResult"
).removeClass(
"loading"
);
$(
"#lblResult"
).html(data.d);
}
function
Error(request, status, error) {
$(
"#lblResult"
).removeClass(
"loading"
);
$(
"#lblResult"
).html(request.statusText);
}
</script>
The CallService function uses the jQuery ajax function to make the call. Most of the options are self explanatory. The url needs to be the name of the web service followed by a forward slash and name of the method to call. The contentType is the type to use when sending data to the server, here I’m using JSON. The dataType tells jQuery what type of data to expect back from the call, here I am also using JSON which evaluates the response as JSON and sends a JavaScript object to the successful callback function. success and error are the functions called upon success or error. I’m not using data here but will use it in the next example to pass parameters to the web service. For a full list of ajax options have a lookhere.You can see that the success function is passed two arguments; the first is the data returned from the call, and the second is some text that represents the status of the call. Here the data can be accessed using ‘data.d’.The error function can have three parameters; the first is the XMLHttpRequest, the second a string describing the error and the third an optional exception object. In this function I am setting the text of the label to the status text of the request on error.Before making the ajax call I add the loading CSS class to the label, which is then removed in each of the callbacks. This shows the animation during the call which is then removed once a response has been recieved. To see this working add the following line to the top of the HelloWorld method in the web service to force a delay:System.Threading.Thread.Sleep(1000);
Now I can run the application and on clicking the button the web service is called and the text ‘Hello World’ will appear in the label… magic…
So the next step would be sending parameters to the web service. Add a new method to the service that looks like this:
[WebMethod]public
int
Add(
int
value1,
int
value2)
{
return
value1 + value2;
}
Now create a new webform like so:
<
table
>
<
tbody
>
<
tr
>
<
th
>
Value 1:
</
th
>
<
td
>
<
asp:TextBox
ID
=
"txtValue1"
runat
=
"server"
/>
</
td
>
</
tr
>
<
tr
>
<
th
>
Value 2:
</
th
>
<
td
>
<
asp:TextBox
ID
=
"txtValue2"
runat
=
"server"
/>
</
td
>
</
tr
>
</
tbody
>
</
table
>
<
asp:Button
ID
=
"btnGo"
Text
=
"Go"
OnClientClick
=
"CallService(); return false;"
runat
=
"server"
/>
<
asp:Label
ID
=
"lblResult"
Text
=
" "
Width
=
"100%"
runat
=
"server"
/>
Upon clicking the button we will pass the values entered in the text boxes to the web service and display the result of the values added together in the label. Here is the jQuery to do this:
<script type=
"text/javascript"
>
function
CallService() {
$.ajax({
type:
"POST"
,
url:
"MyService.asmx/Add"
,
data:
"{ 'value1': "
+ $(
"#txtValue1"
).val() +
", 'value2': "
+ $(
"#txtValue2"
).val() +
"}"
,
contentType:
"application/json; charset=utf-8"
,
dataType:
"json"
,
success: OnSuccess,
error: OnError
});
}
function
OnSuccess(data, status) {
$(
"#lblResult"
).html(data.d);
}
function
OnError(request, status, error) {
$(
"#lblResult"
).html(request.statusText);
}
</script>
The parameters are passed to the web service using the data option. Here I am passing the parameters as a JSON string appending the values from the text boxes on the form. Running this form now allows two values to be entered and the result to be displayed in the label: