Home > asp.net > Consume web service from client side/javascript

Consume web service from client side/javascript

In many scenarios of web application development we come across the point when we need to call some web service from client side or by javascript,

The ASP.NET 2.0 AJAX Extensions enable this exact same experience of seamless proxy generation for Web services for client-side JavaScript that will run in the browser.

You can author an .asmx file hosted on your server and make calls to methods on that service through a client-side JavaScript class. For example, Figure 1 shows a simple .asmx service that implements a faux stock quote retrieval (with random data).

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<strong>[System.Web.Script.Services.ScriptService]  //This is the line used to enable web service from client side</strong>
public class Service : System.Web.Services.WebService
{
public Service () {
//Uncomment the following line if using designed components</div>
//InitializeComponent();
}
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
}
<div><code>
After this you need to add below code to your aspx page,
<asp:ScriptManager ID=”_scriptManager” runat=”server”>
<Services>
<asp:ServiceReference Path=”WebService.asmx” />
</Services>
</asp:ScriptManager>
this will register your web service on client side,to call this web service you just need to write below code:
<div>
<div>&lt;script type="text/javascript"&gt;</div>
<div>function onclick1() {</div>
<div>WebService.HelloWorld(OnLookupComplete);</div>
<div>}</div>
<div>function OnLookupComplete(result) {</div>
<div>var res = document.getElementById("_resultLabel");</div>
<div>res.innerHTML = "&lt;b&gt;" + result + "&lt;/b&gt;";</div>
<div>}</div>
<div>&lt;/script&gt;</div>
</div>
for,
<input onclick=”onclick1();” id=”_lookupButton” type=”button” value=”Lookup” />
Even you can handle your custom events after error or on completion of call to web service like i wrote  “OnLookupComplete” event.
Reference site:

Advertisements
Categories: asp.net
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: