Need help using AJAX to retrieve JSON data from an API

I hope I can get some help as well. I am trying to get JSON info from this same API using AJAX and storing it in a LocalStorage. I was able to do so using another API with the following code:

/* Makes API connection and stores the JSON info into LocalStorage */
var xmlhttp;
if (window.XMLHttpRequest){
    xmlhttp = new XMLHttpRequest();
} else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function(){
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
        var jsondata = JSON.parse(xmlhttp.responseText); //retrieve result as a JavaScript object
        var games_serialized = JSON.stringify(jsondata);

        localStorage.setItem('gamesStored', games_serialized);

But I don’t know how to “setup” the url to use in the place boardgame’s url is right now. Notice that I am sending the “client_id” along with the url here. Do you guys think I can do the same with my token using

Hey @leonidasyopan, couple remarks:

  1. You really shouldn’t post API keys, like client_id regardless of API is free
  2. Did you consider using fetch() instead?

You have to note, that you can only save string key/value pairs, so it would look not pretty at all:

  .then(res => res.json())
  .then(({ games }) => localStorage.setItem('games', JSON.stringify(games)));

I could use fetch, the problem is the URL. I don’t know how to build the URL in order to send the token along.

I need if tor this API:

But I don’t know how to use the token in order to authorize my access. It’s also a free API>

@leonidasyopan If you use XMLHttpRequest, then you just need to make use of the setRequestHeader method to set authorization token in the header.

var url = '';
var xmlhttp = window.XMLHttpRequest
  ? new XMLHttpRequest()
  : new ActiveXObject("Microsoft.XMLHTTP");

xmlhttp.onreadystatechange = function() {
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    var jsondata = JSON.parse(xmlhttp.responseText);
    var { matches } = JSON.stringify(jsondata);
    console.log(JSON.stringify(matches, null, 2));
};'GET', url);
xmlhttp.setRequestHeader("X-Auth-Token", "YourAuthTokenGoesHere");

If you use fetch, then you would need to pass an extra to the fetch call with the headers you want to add.

const url = '';
const options = {
  headers: { "X-Auth-Token": "YourAuthTokenGoesHere" }  
fetch(url, options)
  .then(res => res.json())
  .then(({ matches }) => console.log(JSON.stringify(matches, null, 2)));
1 Like

Thanks so much. The setRequestHeader worked wonderfully.
I really appreciate it.