Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Calling Web Services from JavaScript

5.00/5 (1 vote)
13 Apr 2011CPOL 13.9K  
How to call Web Services from JavaScript

Calling Web Services from JavaScript allows the power of backend processing in your application without a postback, which results in better user experience. JavaScript by default uses the "JavaScript Object Notation" or JSON to communicate with a server. JSON has a shorter length compared with SOAP, and hence is more efficient. It also conforms better to the JavaScript internal object handling system.

If you open a new web site in Visual Studio 2008, the web.config would contain many new sections to enable JSON so many of the necessary framework would already be in place. To call a Web Service from JavaScript, you need to do the following three steps:

  1. Modify the definition of your Web Service (say in MyWebService.asmx.vb) such that the class has an extra attribute as shown below:
    VB
    <System.Web.Script.Services.ScriptService()> _
    Public Class ClassName 
        <WebMethod()> _
        Public Sub MethodName(Parameter As TypeA)
            DoSomething()
        End Sub
    End Class
  2. Use asp:scriptmanager in your ASPX file:
    XML
    <asp:scriptmanager ID="ScriptManager1" runat="server">
    <Services>
    <asp:ServiceReference Path="~/service/MyWebService.asmx" />
    </Services>
    </asp:scriptmanager>
  3. Call the Web Service within a JavaScript function like this:
    JavaScript
    function CallsWebService(anyParametr ) {
      ...;
      NameSpaceName.ClassName.MethodName(anyParameter, OnWSRequestComplete);
    }

The OnWSRequestComplete() function gets called when the Web Service execution finishes. Implement this function as shown below:

JavaScript
function OnWSRequestComplete(results) {
  if (results != null) {
  }
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)