Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my jqxhr.responseText variable undefined, when it's set in the xhr object?

I have a real simple jquery get call here, and I want to use the response later in the script. So if I do this:

var xhr = $.get('cfc/partsDefinition.cfc',{
                method: 'checkValid',
                search: 'some search string'
            }
        );
        console.log(xhr);
        console.log(xhr.responseText);

I can see that A) the first log shows a valid jqxhr object, with a responseText property set to what I expect...

promise: function (a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}
readyState: 4
responseText: "0"
setRequestHeader: function (a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this}

but B) the second log shows "undefined". What am I missing here?

like image 557
earachefl Avatar asked Jan 19 '12 21:01

earachefl


2 Answers

It is showing undefined because at that point in the code, it IS undefined. AJAX is Asynchronous, meaning it doesn't complete before code after it get's ran. The responseText will be undefined until the ajax call is complete. Here's an example:

var xhr = $.get('cfc/partsDefinition.cfc',{
                method: 'checkValid',
                search: 'some search string'
            }
        ).done(function(data){
            console.log("xhr",xhr);
            console.log("xhr.responseText",xhr.responseText);
            console.log("data",data);
        });
console.log("This should happen before the other console logs");
like image 146
Kevin B Avatar answered Sep 27 '22 19:09

Kevin B


Agreed - you're probably dumping it when it's not there; try adding some error handling:

        $.get('cfc/partsDefinition.cfc',{
                method: 'checkValid',
                search: 'some search string'
            },
            function(data, textStatus, jqXHR){ // Success Case
                console.log(data);
                console.log(jqXHR);
            }
        );

        $('.errorContainer').ajaxError(function(event, jqXHR, ajaxSettings, thrownError){
                    $(this).append('ohhhhz noooz - ajax error');
            console.log(event);
            console.log(jqXHR);
            console.log(ajaxSettings);
            console.log(thrownError);
        });

In jQuery the get() shorthand doesn't have any built in error handling - it just supresses it. So if you're trying to catch something you need to make your own error handlers.

http://api.jquery.com/ajaxError/

like image 40
ZapRowsdower910 Avatar answered Sep 27 '22 18:09

ZapRowsdower910