19

I am trying to call an ASMX method from jQuery without success. Following is my code, and I don't understand what I am missing.

File Something.js,

function setQuestion() {
    $.ajax({
        type: "POST",
        data: "{}",
        dataType: "json",
        url: "http: //localhost/BoATransformation/Survey.asmx/GetSurvey",
        contentType: "application/json; charset=utf-8",
        success: onSuccess
    });
}

function onSuccess(msg) {
    $("#questionCxt").append(msg);
}

File SomethingElse.cs,

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Survey : System.Web.Services.WebService {

    public Survey () {
    }

    [WebMethod]
    [ScriptMethod(UseHttpGet = true)]
    public string GetSurvey() {
        return "Question: Who is Snoopy?";
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131

8 Answers8

28

One thing that stands out is you have UseHttpGet=true but in your jQuery code you are using POST.

Also here is a test page I created calling an ASMX page.

[WebMethod]
public Catalog[] GetCatalog()
{
    Catalog[] catalog = new Catalog[1];
    Catalog cat = new Catalog();
    cat.Author = "Jim";
    cat.BookName ="His Book";
    catalog.SetValue(cat, 0);
    return catalog;
}

<script type="text/javascript">
    $(document).ready(function() {
    $.ajax({
            type: "POST",
            url: "default.asmx/GetCatalog",
            cache: false,
            contentType: "application/json; charset=utf-8",
            data: "{}",
            dataType: "json",
            success: handleHtml,
            error: ajaxFailed
        });
    });

    function handleHtml(data, status) {
        for (var count in data.d) {
            alert(data.d[count].Author);
            alert(data.d[count].BookName);
        }
    }

    function ajaxFailed(xmlRequest) {
        alert(xmlRequest.status + ' \n\r ' + 
              xmlRequest.statusText + '\n\r' + 
              xmlRequest.responseText);
    }
</script>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jim Scott
  • 2,493
  • 1
  • 18
  • 16
  • To the extent I understand this, I'm trying to do something similar myself. Can you tell me, since the `[WebMethod]` attribute seems to be supported in regular ASPX files, why is an ASMX file necessary? Thanks. – Jonathan Wood Jun 30 '11 at 19:51
  • Jonathan, if you are creating a method that will only be used for the specific page you are calling the webmethod from then you can definately add it to the page directly. However if you want to use it from multiple pages probably better to create a dedicated asmx for it so it can be reused and does not have a direct relationship with some page. – Jim Scott Aug 08 '11 at 18:17
  • So I hosted the ASMX in IIS in a server, The ASMX has a function `DoTest` which I can click on and it takes me to another page where I can click on "Invoke" button and it displays the XML. However when I tried the above with JQuery call, I get a `0 and error` as the `ajaxFailed` error. Any idea/ – Si8 Jan 19 '17 at 20:18
6

You have to make sure you specify Json as the response format if that is what you want and get rid of UseHttpGet due to security features:

[WebMethod]
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public string GetSurvey() {
    return "Question: Who is Snoopy?";
}
Josef Pfleger
  • 74,165
  • 16
  • 97
  • 99
3

I came across this question and had the same issue. I solved it by adding:

[WebInvoke(Method="POST",ResponseFormat=WebMessageFormat.Json)]

Below your web method attribute, if you'd like to use POST. ie:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class Survey : System.Web.Services.WebService {

    public Survey () {
    }

    [WebMethod]
    [WebInvoke(Method="POST",ResponseFormat=WebMessageFormat.Json)]
    [ScriptMethod(UseHttpGet = true)]
    public string GetSurvey() {
        return "Question: Who is Snoopy?";
    }
}
Jesse
  • 8,223
  • 6
  • 49
  • 81
user609926
  • 801
  • 2
  • 12
  • 25
2

Here is an example of a jQuery call to a page method on an aspx, but it would be similar to an asmx page.

$.ajax(
    {
        type: "POST",
        url: "NDQA.aspx/ValidateRoleName",
        data: '{"roleName":"' + $('[id$=RoleNameTextBox]').val() + '"}',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: ValidateSuccess,
        error: ValidateError

    });
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CSharpAtl
  • 7,374
  • 8
  • 39
  • 53
1

You have to make sure you specify Json as the response format if that is what you want and get rid of UseHttpGet due to security features:

If you read that article then you would see that it is safe to use UseHttpGet as ASP.NET has features to block the cross site scripting attack vector.

There are plenty of valid reasons to use GET.

He can remove the data parameter and change POST to GET to make the call work. Assuming you want a JSON response it would be required to add ResponseFormat=ResponseFormat.Json as well.

Sean Smith
  • 284
  • 2
  • 4
1

The following Steps solved my problem, hope it helps some one,

  1. To allow this Web Service to be called from script, using ASP.NET AJAX, include the following line above your asmx service class for example

    [System.Web.Script.Services.ScriptService] public class GetData : System.Web.Services.WebService {

  2. Add protocols under system.web in web.config, please click on the link if you are not able to view configuration

https://pastebin.com/CbhjsXZj

<system.web>
<webServices>
  <protocols>
    <add name="HttpGet"/>
    <add name="HttpPost"/>
  </protocols>
</webServices>

balaji palamadai
  • 629
  • 2
  • 8
  • 26
1

I would also suggest removing UseHttpGet as Jim Scott suggested.

You can add the following to your options and check the objXMLHttpRequest to see a more detailed error response.

error: function(objXMLHttpRequest, textStatus, errorThrown) {
 debugger;               
}
Rick Hochstetler
  • 3,043
  • 2
  • 20
  • 16
0

If you try chrome browser, try internet explorer it worked for me and also it is about chrome browser you must add extension to works in chrome but i dont know the name of extension

Taha Karaca
  • 111
  • 1
  • 1
  • 10