0

I am working with the Spotify Web Playback SDK and an AJAX function fails whenever I put a variable under the data tag/section. However, when I put the contents of the variable under data, it works flawlessly. window.Thingy is equal to '{"uris": ["spotify:track:2xYlyywNgefLCRDG8hlxZq","spotify:track:3FCto7hnn1shUyZL42YgfO"]}' With variable:

function play(device_id) {
  ListPlaylistTracks(); //Gets output of JSON and saves it to window.Thingy
  $.ajax({
   url: "https://api.spotify.com/v1/me/player/play?device_id=" + device_id,
   type: "PUT",
   data: window.Thingy, //Variable that doesnt work.
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
   success: function(data) { 
     window.dvcID = device_id;
     window.PlayBack = true; 
   }
  });
}

Without variable:

function play(device_id) {
  ListPlaylistTracks();
  $.ajax({
   url: "https://api.spotify.com/v1/me/player/play?device_id=" + device_id,
   type: "PUT",
   data: '{"uris": ["spotify:track:2xYlyywNgefLCRDG8hlxZq","spotify:track:3FCto7hnn1shUyZL42YgfO"]}',
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
   success: function(data) { 
     window.dvcID = device_id;
     window.PlayBack = true;
   }
  });
}

Direct comparison:

data: window.Thingy,

vs

data: '{"uris": ["spotify:track:2xYlyywNgefLCRDG8hlxZq","spotify:track:3FCto7hnn1shUyZL42YgfO"]}',

Any help is greatly appreciated, thanks!

Justluce
  • 29
  • 1
  • If `window.Thingy` were equal to your string literal, then it would work. You must be mistaken about that. – Quentin Nov 26 '18 at 21:28
  • Console.log(window.Thingy) returns '{"uris": ["spotify:track:2xYlyywNgefLCRDG8hlxZq","spotify:track:3FCto7hnn1shUyZL42YgfO"]}' – Justluce Nov 26 '18 at 21:33
  • I bet it only does that later and that `ListPlaylistTracks` is asynchronous. – Quentin Nov 26 '18 at 21:37
  • Doesn't ListPlaylistTracks() have to finish running in order for the next section of the play function to run? – Justluce Nov 26 '18 at 21:45
  • asynchronous asynchronous asynchronous – Quentin Nov 26 '18 at 21:45
  • Probably a duplicate of [this](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) but the question lacks a [mcve] – Quentin Nov 26 '18 at 21:46

0 Answers0