4

UPDATE 1: I haven't figured out what's going on, but this definitely seems to be a problem with my project. After creating a simple test page, I was able to verify that getJSON does in fact return an XHR object like it's supposed to.

UPDATE 2: Wow, this is strange. After doing more testing, I discovered that if I specify the "callback=?" parameter in the URL string the XHR object IS NOT RETURNED properly. If, however, I don't specify the "callback=?" parameter, the XHR object is returned properly. The thing is, I'm calling a JSONP service, so the "callback=?" parameter is required.

Any ideas about why this would be the case?

UPDATE 3: Here are a few standalone code samples to illustrate the issue. In the first sample, console.log(request) is undefined. When I hardcode the callback parameter in the second code sample, console.log(request) is the XHR object.

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    </head>
    <body>
        <script>
            $(document).ready(function() {
                var request = $.getJSON('http://localhost?callback=?', function(data) {

                });
                console.log(request);
            });
        </script>
    </body>
</html>

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
    </head>
    <body>
        <script>
            $(document).ready(function() {
                var request = $.getJSON('http://localhost?callback=callback', function(data) {

                });
                console.log(request);
            });
        </script>
    </body>
</html>

UPDATE 4: Per regilero's comment below, I switched over to using the $.ajax method and passed the parameters up via a data object. Here is the full code for the request:

var request = $.ajax({
    data: {
        f: 'json',
        geometry: '{x:44.203642291681845,y:-95.79085806500001}',
        geometryType: 'esriGeometryPoint',
        imageDisplay: '727,500,96',
        layers: 'all',
        mapExtent: '-179.462733065,16.116769346042226,-51.669764315000016,71.57609342040729',
        returnGeometry: false,
        tolerance: 10
    },
    dataType: 'jsonp',
    success: function(data) {
        console.log(data);
    },
    url: 'http://server.arcgisonline.com/ArcGIS/rest/services/Specialty/Soil_Survey_Map/MapServer/identify'
});
console.log(request);

If I specify "dataType: 'jsonp'" in the config object, console.log(request) is again undefined. If I specify "dataType: 'json'", however, console.log(request) is the XHR object.

This behavior is consistent with what I was experiencing with the $.getJSON shortcut.


ORIGINAL QUESTION

Per the stackoverflow question/answer here: Abort Ajax requests using jQuery and a number of other question/answers on this site and others, the jQuery Ajax methods should return the XHR object.

However, when I run the following code, request is "undefined".

var request = $.getJSON(url, function(data) {
    console.log(data);
});

console.log(request);

Did I miss a change in jQuery? I'm using 1.4.4.

Community
  • 1
  • 1
Nate Irwin
  • 600
  • 1
  • 11
  • 20
  • According to the manual, it should still return a XHR object. http://api.jquery.com/jQuery.getJSON/ Maybe the request fails? – Pekka Jan 07 '11 at 21:31
  • @Pekka: Nope, the request definitely doesn't fail. – Nate Irwin Jan 07 '11 at 21:38
  • Yeah, sorry for that. I misread the question. – Anders Jan 07 '11 at 21:40
  • I tried with a sample code and in my case the console.log(request is working fine), however the conole.log in the callback handler is now getting called – Chandu Jan 07 '11 at 21:45
  • @Cybernate: Yeah, something funky is going on. I just created a test page too, and request is definitely the XHR object. Something funky is going on somewhere in my project. Thanks for helping out with this! – Nate Irwin Jan 07 '11 at 21:49

5 Answers5

5

jsonp does not use XMLHTTPRequest. It is a workaround for the same-origin policy, which applies to all XMLHTTPRequests; it works by inserting <script> tags into the DOM instead, asking the server to return a JSON object wrapped in a JS function denoted by the callback=? parameter.

Since XMLHTTPRequest is not used, no object of that type will be returned.

lonesomeday
  • 233,373
  • 50
  • 316
  • 318
  • This was starting to become obvious! Thanks for verifying. So I guess there is no way to abort a JSONP request, right? I guess the best I can do is ignore returns from "outdated" JSONP requests. – Nate Irwin Jan 07 '11 at 23:19
  • @Nate No, there's no way to abort a JSONP request. – lonesomeday Jan 07 '11 at 23:21
  • For anyone wondering, you can abort script requests (JSONP) by calling window.stop(). This aborts ALL pending image and script requests, though, so it isn't a great solution in most cases. – Nate Irwin Jan 08 '11 at 00:13
  • For anyone following along for the ride, the release of jQuery 1.5 (31 Jan) has overhauled the .ajax() bits completely. Among other things, you now can abort requests, including JSONP requests. Might be worth a read through (http://api.jquery.com/jQuery.ajax/) – Herb Feb 03 '11 at 21:47
1

The $.getJSON function is asynchronous meaning that it will continue running past the script even if the JSON request hasn't finished yet. It's possible that your console.log(request); is running before the request returns and so perhaps it doesn't have the xhr object.

I don't know this for sure, but it's a thought.

EDIT: Below was my original answer which I realize was wrong
The XHR object is passed as the third argument to the callback function. If you want it, you need to use this: function(data, statusText, xhr) { instead of this function(data) {.

Now, if your success callback isn't being called at all, that's another story. Try adding an alert(statusText); in the callback to ensure it's being called. If it's not being called, do as @regilero mentioned and use $.ajax with an error handler passed to see if any error messages are popping up.

  • $.getJSON returns the XHR object, so the fact that it is an asynchronous request shouldn't have anything to do with it. – Nate Irwin Jan 07 '11 at 22:41
0

the first answer is wrong actually you can abort the ajax request ;)

$.ajax({
    url: "/event/search/list-event.html",
    data:{
        page: 1
    },
    beforeSend: function(xhr)
    {    
        if(window.eventListXhr != null){
            window.eventListXhr.abort();
        }
        window.eventListXhr = xhr;
    },
    success: function(data) {
        // ....
    }
});
Fareed Alnamrouti
  • 30,771
  • 4
  • 85
  • 76
0

Wrong Answer. Ignore this post.

$.getJSON doesn't return any value. Instead it gets the response of the URL submitted and converts it to JSON object and passes it to callback if passed. Check the URL: [link text][1] [1]: http://api.jquery.com/jQuery.getJSON/ getJSON method skeleton(as per jQuery Site): > jQuery.getJSON( url, [ data ], [ > callback(data, textStatus, xhr) ] ) > > urlA string containing the URL to > which the request is sent. > > dataA map or string that is sent to > the server with the request. > > callback(data, textStatus, xhr)A > callback function that is executed if > the request succeeds.
Chandu
  • 81,493
  • 19
  • 133
  • 134
0

$.getJSON is a shorthand for $.ajax(), bt like most shorthand of $.ajax() there's no default error handler. Try to use $.ajax and set you error handlers accordingly. Maye something is wrong in your Json syntax. And you're in the 'silent fail' problem.

Doc extract:

Important: As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently. Avoid frequent hand-editing of JSON data for this reason. JSON is a data-interchange format with syntax rules that are stricter than those of JavaScript's object literal notation. For example, all strings represented in JSON, whether they are properties or values, must be enclosed in double-quotes. For details on the JSON format, see http://json.org/.

regilero
  • 29,806
  • 6
  • 60
  • 99
  • Nope, I'm definitely getting a proper response back. See "Update 2" in my original post. There is some new information there. – Nate Irwin Jan 07 '11 at 22:40
  • @Nate about the parameter, you need to urlencode your url or to use the data parameter of $.ajax() to set the parameters of the url. And when you say 'proper response' are you sure it realy good in terms of syntax? – regilero Jan 07 '11 at 22:52
  • 1
    @Nate, I wanted to tell you to add the error handler call in the ajax() parameers, but in the doc I saw "This handler is not called for JSONP requests, because they do not use an XMLHttpRequest". Well if they do not use XMLHttpRequest for JsonP, you cannot get an Xhr result. check http://api.jquery.com/jQuery.ajax/ for jsonp, lot of usefull infos. – regilero Jan 07 '11 at 23:21