Call Web Service from JavaScript using jQuery

Suppose we have the following code behind function which is defined in PrintReport.aspx.cs file.

[WebMethod]
public static  string HelloWorld(string name, string crmId, string comment, string phenotype)
{
      return "Hello World";
}

Now if we want to do ajax call to this function using jquery we will right something like below in our script file.

// Requried  variable initialization is missing.
$.ajax( 
{
        type: 'POST',
        url: 'PrintReport.aspx/HelloWorld',
        dataType: 'json',
        contentType: 'application/json',
        data: "{'name': '" + name + "', 'crmId': '" + crmId + "', 'comment': '" + comment       + "', 'phenotype': '" + phenotype + "'}",
         success: function ( data )
         {
                 alert( data.d );
         },
         error: function ()
         {
          }
} );

Now suppose we have the same method defined in a service named WebServiceTest.asmx

[WebMethod]
public static  string HelloWorld(string name, string crmId, string comment, string phenotype)
{
      return "Hello World";
}

As mentioned above we can have the above block of script in our file and can have a call to the method easily. But unluckily this will not work as the function is defined in a web service. In order to make the functions callable from javascript we must add an attribute to the class in which the service method is defined. The name of this attribute is. This is present in the namespace “System.Web.Script.Services”. If the name of the class is WebServiceTest it will look like as following. [ScriptService] [ScriptService] public class WebServiceTest : System.Web.Services.WebService

{

} Now if you will run your program and try to see the response using firebug we will get a 500 internal server error. The exception generated is “Unrecognized web method HelloWorld”. The above exception can be stopped by making the function non-static. The class having this method will look like following.

[System.Web.Script.Services.ScriptService]

public class WebServiceTest : System.Web.Services.WebService
{
    [WebMethod]
    public  string HelloWorld(string name, string crmId, string comment, string phenotype)
    {
        return "Hello World";
    }
}
150 150 Burnignorance | Where Minds Meet And Sparks Fly!