Search code examples
jqueryhttphandlerashxjquery-callback

JQuery .get() to retrieve JSON response - success callback not triggering


I'm doing the following - it's a JQuery .get() that calls an http handler that should return a JSON object. In the callback function for the .get() (i.e. the third argument passed in the .get() function), which is called when a successful http response is received, the Latitude and Longitude properties of that object are then assigned to a couple of other properties

    var url = "/handlers/GeolocationByIpAddress.ashx";
    $.get(url, {}, function (data) {
        g.currentLat = data.Latitude;
        g.currentLng = data.Longitude;
    });

When I set a breakpoint on the line:

        g.currentLat = data.Latitude;

It isn't hit, which suggests that the success callback isn't triggering. I've checked the request to the .ashx handler in the 'NET' tab of Firebug, and it's showing a successful JSON response with a correctly formed JSON object, with the 'Latitude' and 'Longitude' properties correctly set. I've tried organising the above code a different way so that the callback calls another function and passes the 'data' to it, instead of self-invoking. The separate function is never called, which seems to confirm that the .get() just isn't recognising a successful response. Why would that happen when I can see the successful response in the 'NET' tab of Firebug?


Solution

  • Have you tried using '$.getJSON()' instead?

    $.getJSON(url, function (data) {
        g.currentLat = data.Latitude;
        g.currentLng = data.Longitude;
    });
    

    Have you tested if it fires an error? Try listening to '.fail();

    It seems like '$.get()' should be capable of handling JSON automatically, maybe try telling it your receiving JSON. (Your response headers might be wrong)

    $.get(url, {}, function (data) {
        g.currentLat = data.Latitude;
        g.currentLng = data.Longitude;
    }, "json");