0

responseText returns undefined but when i log it as an object it returns the ajax text. I think it might have something to do with the readystate not being ready before it assigns the text to the variable

When I do this:

function loadTrack(){
    var min = -10;
    var max = 10;
    var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    var track = $.get("generate_song.php?track_number="+randomNumber);
        if(randomNumber > 0 && randomNumber !== previousNumber){
            previousNumber = randomNumber;
        }else{
            randomNumber = 1;
        }

       console.log(track);
}

I get this:

Object {readyState: 1, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
abort: function (e){var t=e||w;return u&&u.abort(t),k(0,t),this}
always: function (){return i.done(arguments).fail(arguments),this}
complete: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
done: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
error: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
fail: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
getAllResponseHeaders: function (){return 2===b?a:null}
getResponseHeader: function (e){var t;if(2===b){if(!c){c={};while(t=Tn.exec(a))c[t[1].toLowerCase()]=t[2]}t=c[e.toLowerCase()]}return null==t?null:t}
overrideMimeType: function (e){return b||(p.mimeType=e),this}
pipe: function (){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()}
progress: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
promise: function (e){return null!=e?x.extend(e,r):r}
readyState: 4
responseText: "Audio_Files/09%20Dream%20of%20Witches%20Dinner%2C%20V%20mov.%20f.m4a.mp3<br/>"
setRequestHeader: function (e,t){var n=e.toLowerCase();return b||(e=v[n]=v[n]||e,y[e]=t),this}
arguments: null
caller: null
length: 2
name: ""
prototype: Object
__proto__: function Empty() {}
<function scope>
state: function (){return n}
status: 200
statusCode: function (e){var t;if(e)if(2>b)for(t in e)m[t]=[m[t],e[t]];else C.always(e[C.status]);return this}
statusText: "OK"
success: function (){if(l){var t=l.length;(function i(t){x.each(t,function(t,n){var r=x.type(n);"function"===r?e.unique&&p.has(n)||l.push(n):n&&n.length&&"string"!==r&&i(n)})})(arguments),n?o=l.length:r&&(s=t,c(r))}return this}
then: function (){var e=arguments;return x.Deferred(function(n){x.each(t,function(t,o){var a=o[0],s=x.isFunction(e[t])&&e[t];i[o[1]](function(){var e=s&&s.apply(this,arguments);e&&x.isFunction(e.promise)?e.promise().done(n.resolve).fail(n.reject).progress(n.notify):n[a+"With"](this===r?n.promise():this,s?[e]:arguments)})}),e=null}).promise()}
__proto__: Object

But when I do This:

function loadTrack(){
    var min = -10;
    var max = 10;
    var randomNumber = Math.floor(Math.random() * (max - min + 1)) + min;
    var track = $.get("generate_song.php?track_number="+randomNumber);
        if(randomNumber > 0 && randomNumber !== previousNumber){
            previousNumber = randomNumber;
        }else{
            randomNumber = 1;
        }

       console.log(track.responseText);
//or if i just do it when assigning track
}

I get this:

undefined script.js:41
XHR finished loading: "http://localhost/generate_song.php?track_number=10". jquery.js:6
user2426607
  • 29
  • 1
  • 5
  • 1
    AJAX is Asynchronous. – Kevin B May 29 '13 at 15:14
  • I'm sorry, I dont understand – user2426607 May 29 '13 at 15:16
  • possible duplicate of [How to return the response from an AJAX call?](http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call) – James Montagne May 29 '13 at 15:16
  • @user2426607 Think of it this way. an ajax request is like a setTimeout with an unknown delay. The code after it will execute before the setTimeout callback executes because it executes after the delay, the delay in this case being how long it takes to get the data. The data won't be available until after said delay. – Kevin B May 29 '13 at 15:20

2 Answers2

0

You are kindof right, it is a timing problem. The jqXHR-Object exists, but responseText doesn't at the time you are assigning the object. But at the time of logging it does show. You shouldn't see the property of responseText if you log using console.log(JSON.stringify(track)).

So, wait for the reply by using a callback for readyStateChange or alike mechanisms.

The problem comes with the logging functionality (I assume firebug or chrome's inspector?) that does not really freeze the object but show's it as it is at the time you look.

Hoffmann
  • 1,050
  • 9
  • 26
-1

You are trying to use the results of the ajax call before the call has been completed. Javascript will keep executing all the code after the call has been made. Since you don't have any data, it is null until the call has been completed.

You want to modify your $.get() and pass it a function to execute when the call has been completed.

$.get("generate_song.php", {track_number: randomNumber}, function(track){
     console.log(track);
});

You can also just send the parameters without creating the url.

http://api.jquery.com/jQuery.get/

Schleis
  • 41,516
  • 7
  • 68
  • 87