0

I am trying to call webservice method from Jquery ajax.

Here is my jquery code,

function abc() {

        alert("");
        $.ajax({
            type: "Get",
            url: "abc.asmx/HelloWorld",
            data: "{}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            error: function (errorThrown) {
                console.log(errorThrown.d); 
                alert(errorThrown + "what's wrong?");
            },
            success: function (msg) {
                console.log(msg.d);
                alert(msg.d);
                return false;
                // Do something interesting here.
            }
        });
        return false; }

and my web method is following,

 [WebMethod]
public string HelloWorld() {
    return "Hello World";
}

the jquery error event is keep occuring. Not sure why it's happening

any help will be appreciated

thanks

fc123
  • 898
  • 3
  • 16
  • 40

3 Answers3

1

I was missing the [ScriptService] attribute on my WebService class, similar to this:

[ScriptService]
public class MyWebService : System.Web.Services.WebService 
{
    [WebMethod]
    public string HelloWorld() {
        return "Hello World";
    }    
}

Now it's working perfectly.

Nope
  • 22,147
  • 7
  • 47
  • 72
fc123
  • 898
  • 3
  • 16
  • 40
  • 1
    I added some sample code how this might look like so future users with less knowledge in the area may find this useful. If this is not how you used it, please add your sample code showing the solution. – Nope Aug 26 '14 at 15:26
0

Try this as you are expecting a JSON result from server and adding ScriptMethod will enable javascript to call your method

[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public string HelloWorld()
{
 return "Hello World";
}

Also check How to let an ASMX file output JSON

Community
  • 1
  • 1
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120
-2

I guess that you need to specify what kind of request the method will response.

something like this

[HttpGet]
public string HelloWorld() {
    return "Hello World";
}

Or use the convention

public string Get() {
    return "Hello World";
}
rcarvalho
  • 790
  • 1
  • 4
  • 14