Javascript - API request with XMLHttpRequest, xhr.onload function - map error

Hi,

I’ve spent hours on this issue. My GET code to OMDB API is below.
Works fine when a user enters in a movie title in a search field in my form, however if the
search results (sent back) returns 0 / no movies found, I want to inform the user via alert (for example if statement) or a message in the HTML (innerhtml for ex). Any suggestions on how to add this in correctly?

Issue: When I enter in for example something random ‘sodis’, I get an Error in my console log. ’ TypeError: Cannot read property ‘map’ of undefined’.
I guess its because the data sent back isn’t an array? How do I solve this?

function makeRequest(searchTitle) {
  var xhr = new XMLHttpRequest();
  xhr.onload = function() {
    var response = JSON.parse(this.responseText).Search;
    response.map(function(item) {
      movieResult("omdb", item.Title, item.Year);
    });
  };
  
  xhr.open("GET", url + searchTitle, true);
  xhr.send();
}

Movieresult and SearchTitle are defined in other functions.

var url = "https://www.omdbapi.com/?apikey=" + apiKey + "&type=movie" + "&s=";

Welcome, lou_ise.

There are a few ways you can handle this:

  1. Check if the response contains useful information:
if (Array.isArray(response)) {
  // Do stuff
} else {
  // Warn user
}
  1. Just catch the errors (not usually a nice UX choice, but more robust than 1)
try {
  response.map(,,,)
} catch (err) {
  // Warn user there is has been an error
}

If i were a user with this kind of search, I would expect to see something like:

<p>No results matched {userQuery}...</p>

Hope this helps

thanks for your quick reply. I’m trying option 2 with catch error, but there is something still wrong, now nothing is returned even though I input into the search field a correct movie title. Can you please assist how you would write the catch error code in my function? I tried the below:

var apiKey = "36e234cd";
var url = "https://www.omdbapi.com/?apikey=" + apiKey + "&type=movie" + "&s=";

//Denna funktion hämtar och skickar data från API och konverterar från JSON data till Javascript
function makeRequest(searchTitle) {
  var X = new XMLHttpRequest();

  X.onload = function() {
    var response = JSON.parse(this.responseText).Search;
    //callback function
    try {
    response.map(function(item) {
      movieResult("omdb", item.Title, item.Year);
    });
  }
  catch (err) {
    alert ("no");
  }
  
  X.open("GET", url + searchTitle, true);
  X.send();
};
}

many thanks,

Louise

If I try option 1, no search result is returned (receiving data is blocked somehow?) and I get the following console log error: Uncaught TypeError: Cannot read property ‘map’ of undefined

var apiKey = "36e234cd";
var url = "https://www.omdbapi.com/?apikey=" + apiKey + "&type=movie" + "&s=";

//Denna funktion hämtar och skickar data från API och konverterar från JSON data till Javascript
function makeRequest(searchTitle) {
  var X = new XMLHttpRequest();

  X.onload = function() {
    var response = JSON.parse(this.responseText).Search;
    //callback function
    if (Array.isArray(response)) {
  alert ("oh no");
} else {
  response.map(function(item) {
      movieResult("omdb", item.Title, item.Year);
    });
  }
};
    
    
    
  
  X.open("GET", url + searchTitle, true);
  X.send();
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).


You have not quite followed the logic for the option I gave with 1. Only if the response is an array, should it be mapped over…

For the try...catch you seem to have mixed up where the X.onload function should end. There should be a } (closing bracket) after the catch block.

Hope this helps.

Ideally, if you would like more help with this, it would be easier to work off of an actual project. To share your project you could use one of the following: CodePen, CodeSandbox, Repl.it, Glitch.

Unless there is a specific reason why you are using XMLHttpRequest I would suggest using fetch instead (youtube videos).

Also, if you are not going to return anything from map you shouldn’t be using it, use forEach instead if you just want to loop an array.

1 Like