Reputation: 801
I am trying to make api call to get spotify albums in native javascript without using any js frameworks. I am running into issues where I am unable to send Oauth token using native js. For spotify I have client id and client scret. I can either use that or the Oa
(function() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://api.spotify.com/v1/albums", false);
xhr.send();
document.getElementById("results").innerHTML = xhr.responseText;
})();
Upvotes: 1
Views: 3482
Reputation: 360
function request(callback) {
var xobj = new XMLHttpRequest();
// true parameter denotes asynchronous
xobj.open('GET', YOUR_URL_HERE, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
// This marks that the response has been successfully retrieved from the server
// Utilize callback
callback(xobj.responseText);
}
};
xobj.send(null);
}
I would definitely recommend taking a look at the link Frobber provided. It's always better to understand why something does/doesn't work rather than just getting it to work. Here is a mock request to get you started. Hope this helps!
Upvotes: 1
Reputation: 18022
I think you need to read a basic tutorial on how to use XMLHttpRequest, which you can find here
One immediate problem with your code is that it's not using any callback to read the result that comes back from the server. This is all happening asynchronously, so what's occurring in your case is that you're send()
ing the request, and then immediately setting innerHTML
to a value that probably isn't even available from the server yet.
Check the tutorial for how to get that information back from the server when it's ready.
Note the use of the myFunction
callback, and note the use of onreadystatechange
. What's happening here is that send()
is sending something to the server, in a separate execution thread. You need to register a callback function that will perform the data fetching and DOM update when the server reports back that the data is available, not immediately.
Upvotes: 0