Calling Web Services from JavaScript





5.00/5 (1 vote)
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:
- Modify the definition of your Web Service (say in MyWebService.asmx.vb) such that the class has an extra attribute as shown below:
<System.Web.Script.Services.ScriptService()> _ Public Class ClassName <WebMethod()> _ Public Sub MethodName(Parameter As TypeA) DoSomething() End Sub End Class
- Use
asp:scriptmanager
in your ASPX file:<asp:scriptmanager ID="ScriptManager1" runat="server"> <Services> <asp:ServiceReference Path="~/service/MyWebService.asmx" /> </Services> </asp:scriptmanager>
- Call the Web Service within a JavaScript function like this:
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:
function OnWSRequestComplete(results) {
if (results != null) {
}
}