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.

2 Answers 2

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`);
Sign up to request clarification or add additional context in comments.

2 Comments

Why did you answer work and not mine? I read an answer in this thread: stackoverflow.com/questions/19105009/…
@PhilipCarlsson see my answer for this question
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.