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?
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");
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With