0

I'm very new to JavaScript and have been looking for a solution for a while with no success. I'm trying to use the Last.fm API to retrieve the currently playing track on my account. This is what I have so far:

<html>
    <body>
        <p>this is an experiment!</p>
        <script type="text/javascript">
            const request = new XMLHttpRequest();

            request.open('GET', 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user='+[MY_USERNAME]+'&api_key='+[MY_API_KEY]+'&format=json');
            request.send(); 

            request.onload = () => {
                if (request.status === 200) {
                    console.log("Success");

                    var song = JSON.parse(request.response).recenttracks.track[0].name;

                    console.log(song);  
                } 
            };

            request.onerror = () => {
            console.log("error")
            };
        </script>
    </body>
</html> 

and I get an error in the console when I open the file in my browser. Any help is appreciated :)

Update: everything worked when I gave it the direct URL, e.g. I took out the +s and put the API key directly in.

2 Answers2

2

I checked your code with the test-account and it works fine. So probably you get the empty result, let's add some checks:

request.onload = () => {
    if (request.status === 200) {

        // look at the response
        console.log(request.response);

        const recenttracks = JSON.parse(request.response).recenttracks;

        if (!recenttracks.track || !recenttracks.track.length) {
          console.log('track is empty');
          return;
        }

        const song = recenttracks.track[0].name;

        console.log(song);  
    } 
};
vladimir
  • 13,428
  • 2
  • 44
  • 70
1

It looks like you should use onreadystatechange to catch the response instead of onload.

Example:

request.onreadystatechange = function() {
  if (this.status == 200) {
    console.log(this.responseText);
  }
};

You can read more about XMLHttp Requests here: https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

Dimitrios Matanis
  • 896
  • 1
  • 6
  • 19
  • Should be noted that the last.fm API sometimes uses the 200 http status code to return errors. This is a flaw in their design, but something you need to watch out for. – Thom May 06 '20 at 08:18