Unable to call aspx page web method using jquery ajax

16,921

Solution 1

Two things:

  1. You are missing the contentType in your jQuery .ajax() function.
  2. You need to account for the .d value in the JSON response.

    $.ajax({
        type: "POST",
        url: "Default.aspx/Hello",
        data: "{}",
        async: false,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(result) {
            if (result.hasOwnProperty("d")) {
                // The .d is part of the result so reference it
                //  to get to the actual JSON data of interest
                console.log('Success: ', result.d);
            }
            else {
                // No .d; so just use result
                console.log('Success: ', result);
            }
        }
    });
    

Note: The .d syntax was an anti-XSS protection put in by Microsoft in the ASP.NET 3.5 release of ASP.NET AJAX; therefore the check to see if the .d property is there or not.

Solution 2

You could code like this: (This works for me very well) I used jquery from CDN: "http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"

public class MyClass
{
    public string myName
    {
        get { return "Hello"; }
    }
}

In your aspx.cs page:

[WebMethod]
[System.Web.Script.Services.ScriptMethod(ResponseFormat = System.Web.Script.Services.ResponseFormat.Json, UseHttpGet = true)]
public static object MyMethod()
{
    return new MyClass();
}

And in your ASPX page:

$.ajax({
            url: "somepage.aspx/MyMethod",
            data: {},
            cache: false,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            type: "GET",
            success: function (data) {
                if (data.hasOwnProperty("d"))
                    alert(data.d.myName);
                else
                    alert(data);
            },
            error: function (reponse) {
                alert(reponse);
            }
        });
Share:
16,921
iJade
Author by

iJade

JavaScript enthusiast

Updated on June 14, 2022

Comments

  • iJade
    iJade almost 2 years

    Getting aspx page html when trying to call web method on aspx page.Here is the jQuery code

      $(function () {
            $.ajax({
                type: 'POST',
                url: 'Default.aspx/Hello',
                data: "{}",
                async: false,
                success: function (response) {
                    console.log('Success: ', response);
                },
                error: function (error) {
                    console.log('Error: ', error);
                }
            });
        });
    

    And here is the web method code

     [System.Web.Services.WebMethod]
        public static string Hello()
        {
            string returnString = "hoiiiiiii";
            return returnString;
        }
    

    Can any one point out what may be wrong.