Click here to Skip to main content
15,887,746 members
Articles / Web Development / ASP.NET

Calling Web Services from JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
13 Apr 2011CPOL 13.6K   5   1
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) {
  }
}
This article was originally posted at http://morrisbahrami.blogspot.com/feeds/posts/default

License

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


Written By
Architect
Australia Australia
I have over 17 years of experience in software development in a variety of fields. For last 7 years the emphasis has been mostly on .NET technology (C# and VB.NET) which includes WPF, WCF and ASP.NET AJAX. Also have SQL Server experience including SSIS and SSRS. My blog (http://morrisbahrami.blogspot.com) has a collection of tips and general info for Microsoft Developers.

Comments and Discussions

 
Generaltips for getting return value of webservice method Pin
Lijo John v19-Apr-11 1:46
Lijo John v19-Apr-11 1:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.