8

I am trying to call a WebMethod from JavaScript. So far I have:

The EMSWebService.asmx:

namespace EMSApplication.Web.WebServices
{
    /// <summary>
    /// Holds the Webservice methods of EMSApplication
    </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]     
    [System.Web.Script.Services.ScriptService]
    public class EMSWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

In the aspx page I have added the followings:

<asp:ScriptManager ID="ScriptManager" runat="server">
    <Services>
        <asp:ServiceReference Path="~/WebServices/EMSWebService.asmx" />
    </Services>
</asp:ScriptManager>
<input onclick="callWebMethod();" id="btn" type="button" value="Click Me" />

And the JavaScript is:

<script type="text/javascript">
    function callWebMethod() {
        EMSApplication.Web.WebServices.EMSWebService.HelloWorld(OnComplete, OnError);            
    }

    function OnComplete(result) {
        alert(result);
    }

    function OnError(result) {
        alert(result.get_message());
    }

</script>

But the method is not executing. I am getting following JavaScript error:

EMSApplication not defined.

Is there anything I am missing? Do I need to do some other configuration?

The Project structure is depicted below:

enter image description here

JavaScript and components is in Login.aspx.

Is there any significance of the URL of [WebService(Namespace = "http://tempuri.org/")]


Edit:

I have also tried this by using jQuery and modify the aspx page as:

$(document).ready(function () {
        $("#btn").click(function () {                
            $.ajax({
                type: "POST",
                url: "../WebServices/EMSWebService.asmx/HelloWorld",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);                        
                },
                failure: function (msg) {                        
                    alert(msg.d);
                }
            });
            return true;
        });
    });

I have written System.Diagnostics.Debug.WriteLine("Hello World"); inside the WebMethod, it is executing that i.e., it is printing "Hello World" in the Output Window of the Visual Studio but I am not getting any alert message.

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Tapas Bose
  • 28,796
  • 74
  • 215
  • 331
  • Set a breakpoint on the client-side, e.g. inside Google Chrome's excellent developer tools to see what happens before/after the ajax call. – Uwe Keim Mar 24 '12 at 18:28
  • Can you verify that the scripthandlerfactory is defined in the web.config? – Jeremy Howard Mar 24 '12 at 18:30
  • No I didn't defined any scripthandlerfactory in web.config. What should I do? – Tapas Bose Mar 24 '12 at 18:33
  • 1
    Read here http://msdn.microsoft.com/en-us/library/bb398998.aspx this page goes over what you need to do to call webservices from script. – Jeremy Howard Mar 24 '12 at 18:45
  • @JeremyHoward can you post your answer. So that I can accept it. It is solved after using `` in the `` of ``. Thank you very much. – Tapas Bose Mar 24 '12 at 18:47
  • @JeremyHoward can you tell me what is the significance of `[WebService(Namespace = "http://tempuri.org/")]` – Tapas Bose Mar 24 '12 at 18:50

2 Answers2

8

I wanted to answer the question directly.

I have a WebMethod, sitting in a SomePage.aspx file:

[WebMethod]
public static String DoSomething(String shiftName)
{
    return shiftName+" hi there";
}

The question is: How do i call this web method? Since this is HTTP, the answer is to to an HTTP POST to the server:

POST http://localhost:53638/SomePage.aspx/DoSomething HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: qps-ploc,en-US;q=0.5
Accept-Encoding: gzip, deflate
Host: localhost:53638
Connection: Keep-Alive
Content-Length: 23
Content-Type: application/json;charset=utf-8

{'shiftName':'contoso'}

The critically important things to note are:

  • HTTP method: POST (GET will not work)
  • you specify the name of you method on the aspx page as SomePage.aspx/[MethodName]. In this case:

    SomePage.aspx/DoSomething

  • you pass the parameters of the method as JSON. This method has one string parameter: shiftName. This means i constructed the JSON:

    {'shiftName':'contoso'}
    
  • with the request's JSON content type, you have to specify the Content-Type request header:

    ContentType: application/json;charset=utf-8
    

Given that my example WebMethod simply takes the supplied text, appends hi there, and returns that string, the response from the web-server is:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 24
Connection: Close

{"d":"contoso hi there"}

Where the HTTP response body is also a JSON string, with a single property called d. I don't know where they got d from, but there it is.

That's how you call a WebMethod using http (e.g. assembly language, COM, C#, Java, Delphi).

The most common question is how do you call it from the client using jQuery.

$.ajax({
       type: "POST",
       url: 'Catalogo.aspx/checaItem',
       data: "{ id : 'teste' }",
       contentType: 'application/json; charset=utf-8',
       success: function (data) {
           alert(data);
       }
});

Note: Any code released into public domain. No attribution required.

Ian Boyd
  • 246,734
  • 253
  • 869
  • 1,219
3

You need to make sure that you have the scripthandlerfactory defined in your web.config...more here http://msdn.microsoft.com/en-us/library/bb398998.aspx

  • Thank you. Can you tell me what is the significance of [WebService(Namespace = "http://tempuri.org/")] – Tapas Bose Mar 24 '12 at 19:03
  • Tapas, the namespace of your service is to provide consumers of your service a unique service location. This is to prevent services from clashing if they have the same service name. Before going to production you will want to change the namespace to something more unique. More on the subject here... http://social.msdn.microsoft.com/forums/en-US/asmxandxml/thread/ad85151b-868e-4c30-9bfc-a0c0affb6827/ – Jeremy Howard Mar 24 '12 at 19:46