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
  • 24,690
  • 13
  • 50
  • 55

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
  • 24,690
  • 13
  • 50
  • 55
0

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

Titouan56
  • 6,932
  • 11
  • 37
  • 61