Why is my jqxhr.responseText variable undefined when set in an xhr object?

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

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

I see that A) the first log shows a valid jqxhr object whose responseText property is as expected ...

 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?

+4
source share
2 answers

It shows undefined because at this point in the code it is undefined. AJAX is asynchronous, which means that it will not complete before the code after it runs. responseText will be undefined until the ajax call completes. Here is 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"); 
+3
source

I agree - you probably discard it when it is not there; try adding 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 shorthand get() expression does not have built-in error handling - it just cancels it. Therefore, if you are trying to catch something, you need to make your own error handlers.

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

+1
source

Source: https://habr.com/ru/post/1391931/


All Articles