Using a variable in an api request header field

Using a variable in an api request header field
0

#1

I’m working on the wikipedia viewer project and am having trouble trying to get the api to search the results from my form input. The “result” variable represents my input value from my index page.
The code seems to work fine if I hard code something into the search field in the request header. You’ll see the word “hello” there now. I’ve been trying to somehow use “result” in that field by using string concatination but the an error in the console that says “search must be set”. I’m not sure how to alter the header in such a way to fit that variable in there. Help will be appreciated.

$('#search').keypress(function () {
  let result = document.getElementById('search').value;
  $.ajax({
    url: 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=hello&prop=revisions&rvprop=content&formatversion=2',
    dataType: 'jsonp',
    type: 'GET',
    success: function (data) {
        console.log(data);
        for (var i = 0; i < 10; i++) {
          $('.container').append('<div class="content">' + data[1][i] + '<br><br>' + data[2][i] + '</div>');
        }
     }
  });
});```

#2

Just clarifying, but you did try
url: 'https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + result + "&prop=revisions&rvprop=content&formatversion=2' right?


#3

I just tried it and it hard codes the word “result” unfortunately.


#4

Can you post a link to your project so we can check out a few things?


#5

Sorry about that. I usually build it in an editor first. Totally forgot to transfer it to codepen and share the link.


#6

See the post above where @n_haniph suggests what your url property value should look like.

You also have a couple other issues.

  1. Try using keyup instead of keypress.

  2. Because you are using $(’.container’).append in your for loop, make sure to clear out the html div with class=“container” before the for loop. If you do not, then within the same session, when a user types new words into the search box, they will keep getting appended to the container without replacing the first results.


#7

Thanks for the info! It works great now! The help is very appreciated!