How to call webmethod from javascript
In some cases you may want to call the webmethods from javascript. In that cases we use JQuery ajax call. WebMethods are written in WebServices and we have to provide url of that webmethod in javascript in order to call that webmethod. In this post i am explaining how we can do this with a example.
Generally WebMethods are written in WebServices. We can write WebMethods in our code behind files also.
Type 1: Calling WebMethod which is written in "CodeBehind" file
In order to call WebMethods which are in code behind files, you have to declare those WebMethods as static and you have to put [WebMethod] attribute at the begining of the method.
Syntax:
[WebMethod]
public static SomeName()
{
//some code
}
you have to add using System.Web.Services; name space to your code behind file.
Type 2: Calling WebMethod which is written in WebService
In order to call the WebMethod which is written in WebService you don't need to use static keyword for that WebMethod.
First, look at this code in youe WebService
namespace callingWebMethod
{
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
}
Look at the 10th line in the code.
So, in order to call WebMethod from javascript you have to uncomment the 12th line. Now, you are able to call that method from your javascript.
Using Ajax call
You have to use JQuery Ajax to call WebMethod. The code look like this,
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "WebService.asmx/yourWebMethodName",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
//here data.d is the returned value from WebMethod
},
Error: function (status) {
alert(status.code + "" + status.Message);
}
})
Note: Careful with the url. If the url is wrong then the WebMethod will not be called.
The above code calls the WebMethod and if that WebMethod returns anything(sring or int etc) then that will be stored in data.
Note success anf Error functions written above. The success function is invoked when a WebMethod is called succesfully and the Error function is invoked when there is a error in calling the WebMethod.