1

I'm trying to connect to an API. By doing this with a static string, it works fine, but when I'm doing it by using a variable, it seems not to work.

This is how my code looks:

var movie = 'taken';

OurRequest.open('GET', 'http://www.omdbapi.com/?s=${movie}&apikey=222222');
OurRequest.onload = function() {
  console.log(OurRequest.responseText);
};
OurRequest.send();

So when I remove ${movie} and replace it with 'taken' as a string, it works fine.

Racil Hilan
  • 23,737
  • 12
  • 48
  • 51

2 Answers2

2

Not every browser supports JavaScript Template literals. You can concatenate the value like this:

OurRequest.open('GET', 'http://www.omdbapi.com/?s=' + movie + '&apikey=222222');

If you really want to use JavaScript Template literals, then you need to enclose the entire string in back ticks, not the usual single or double quotes. Like this:

OurRequest.open('GET', `http://www.omdbapi.com/?s=${movie}&apikey=222222`);
Racil Hilan
  • 23,737
  • 12
  • 48
  • 51
0

You should use backquote "`" to interpolate your variable inside your string. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

Epitouille
  • 6,422
  • 10
  • 34
  • 58