Bodzilla Bodzilla - 4 months ago 8
Javascript Question

Ajax call doesn't return success

I have an Ajax call which returns an JSON object, within the object is a property that states if the call was a success or not. For some reason, even if the call comes back as a success, the AJAX never hits it, in-fact it always returns as a failure. Not sure why.

AJAX:

function GetSubTaskStories() {
$.ajax({
type: "POST",
url: "Story.aspx/GetSubTaskStories",
data: JSON.stringify({ id: GetSubTaskID() }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.success) {
alert("Success: True");
} else {
alert("Success: False");
}
},
error: function (data) {
}
});
}


SERVER:

[WebMethod]
public static string GetSubTaskStories(string id)
{

// Do some stuff.
JavaScriptSerializer jss = new JavaScriptSerializer();
try
{
var storiesObj = new { success = true, stories = stories };
return jss.Serialize(storiesObj);
}
catch (Exception ex)
{
var error = new { success = false };
return jss.Serialize(error);
}
}

Answer

You're returning an object with a property d that is a string that contains the serialized version of your result. It's not easy to see from your example with all the quotes and escaped quotes.

Remove the jss.serialize and return the anonymous object as your result.

[WebMethod]
public static object GetSubTaskStories(string id)
{

    // Do some stuff.
    JavaScriptSerializer jss = new JavaScriptSerializer();
    try
    {
        var storiesObj = new { success = true, stories = stories };
        return storiesObj;
    }
    catch (Exception ex)
    {
        var error = new { success = false };
        return error;
    }
}