How to consume a webservice using javascript ?

I wrote this blog because there are few resources that elaborate on client-side consuming a Web service. This type of consuming is very handy when one has to make Web service calls to a remote Web server directly from the client. Those who can think of many instances where one would want to make Web service calls from the client.Let us see here how to consume a webservice using javascript ?.Here I am explaining the very simple way to invoke a webmethod from javascript . It is really interesting. .
Step 1:
Add Script Manager Instance to your ASPX Page, Here i have specified path of my webservice (test.asmx).
<asp:ScriptManager ID="_ScriptManager" runat="server">
<Services>
<asp:ServiceReference Path="~/test.asmx" />
</Services>
</asp:ScriptManager>

Step 2:
a ) Open the file test.asmx.cs then add below mentioned attribute to your code if it is not present

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]

b ) create a public webmethod in the test.asmx.cs.

[WebMethod]
public string GetSum(int value)
{
return (value + 1).ToString();
}

okey, Now let us see how we can invoke this webmethod from javasript.

step 3:
function javaSriptMethod()
{
Test.GetSum(2, OnLookupComplete)
}

Define result Handler Function as Depicted in above code


function OnLookupComplete(result)
{
alert(result);
}

thank you!

Leave a Reply

Your email address will not be published. Required fields are marked *