views:

130

answers:

3

I am doing an ajax call using jquery to get data in json format. the success callback function is called but the data is empty.

$(document).ready(function () {
    $.ajax({
        url: "http://apps.sungardhe.com/StudentResearch/public/Research.svc/Schools",
        type: "GET",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: cbSchools
    });
});

function cbSchools(data) {
    if (data == null) {
        alert("data is null");
        return;
    }
    for (var school in data) {
        $("#ddSchool").append("<option value='" + data[school].ShortName + "'>" + data[school].ShortName + "</option>");
    }
}

using fiddler I see that the response is actually returning the json data but for some reason the jquery result object is null. can anyone tell me why?

A: 

try this

if (data.d == null) {
    alert("data.d is null");
    return;
}

since your return datatype is json, the data is in the data, "d", variable in the response object.

marduk
If `data` is null already, how can it have a property? :) This will just throw an error on the `if()` statement itself.
Nick Craver
if you try to access data.d you get the javascript error "data is null"
rushonerok
+3  A: 

You're being blocked by the same-origin policy which prevents cross-domain XMLHttpRequests. Since you need to set headers to get JSON back from a .Net web service like this, you're in a tough spot, you just can't make that kind of request from a browser, not from a different domain.

Fiddler may be showing the content, but the browser isn't going to let the page see it, for security reasons it'll always be null. The one way around this is JSONP, but unfortunately it doesn't look like that service is setup to support it.

Nick Craver
+1  A: 

I believe you can make your calls generic (reason as marduk indicates)

To handle this, and to make calls generic (works with data and data.d), I use the following in my ajax calls (with my asp.net stuff) so that it works with older as well as newer services:

   dataFilter: function(data)
    {
        var msg;
        if (typeof (JSON) !== 'undefined' &&
        typeof (JSON.parse) === 'function')
            msg = JSON.parse(data);
        else
            msg = eval('(' + data + ')');
        if (msg.hasOwnProperty('d'))
            return msg.d;
        else
            return msg;
    },

EDIT: IF it is truly null AND NOT "undefined" then the cross domain issue might be in play here.

Mark Schultheiss
There's no need to handle it yourself, this is already doing done, aside from the `.d`. When getting JSON jQuery [uses `$.parseJSON()`](http://github.com/jquery/jquery/blob/master/src/ajax.js) which already checks for browser abilities (like `JSON.parse()`), and checks it for validity, etc, take a look yourself here: http://github.com/jquery/jquery/blob/master/src/core.js#L483
Nick Craver