0

I'm trying to use my text input as a string variable and use that variable as a part of a URL to pull up JSON data but I can't seem to get it to work properly.

I don't know if I'm setting the variables incorrectly but any help would be appreciated. Thank you!

$(document).ready(function() {
    var p = document.querySelector('p');
    var input = document.getElementById('search').value;
    $("#go").click(function() { 
        if (input === '') {
            p.style.backgroundColor = 'transparent';
            p.classList.add = 'hide';
            p.innerHTML = '';
        } else {
            $.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + input + "&callback=?", function(data) {
                p.innerHTML = "<br> Click the links below";
                p.classList.remove('hide');
                var i = 0
                for (i; i < 5; i++){
                    if (data[3][i] !== undefined){
                        p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>' 
                    } else {
                        p.innerHTML = ' <h2> No matching result </h2>';
                    }
                }
            });
        }
    });
});
leo
  • 8,106
  • 7
  • 48
  • 80
Joon Park
  • 3
  • 5

1 Answers1

0

At the time you assign the variable value, it is empty because it is run when the site is loaded and there is probably no text in the search box yet. You want the content at the time #go is clicked, so just assign it inside the click event handler:

$(document).ready(function() {
var p = document.querySelector('p');
// the text field value is empty at this point

$("#go").click(function() { 
  // this is run when user clicks #go
  var input = document.getElementById('search').value;
  if (input === '') {
    p.style.backgroundColor = 'transparent';
    p.classList.add = 'hide';
    p.innerHTML = '';
  }
  else {
  // encode user input
  $.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=" + encodeURIComponent(input) + "&callback=?", function(data) {
    p.innerHTML = "<br> Click the links below";
    p.classList.remove('hide');
    var i = 0
    for (i; i < 5; i++){
      if (data[3][i] !== undefined){
      p.innerHTML += '<h2> <a href ="' + data[3][i] + '" target = "_blank">' + data[1][i] + '<br>' + '<h3>' + data[2][i] + '</h3>' + '</h2>' 
    }

    else {
      p.innerHTML = ' <h2> No matching result </h2>';

    }
    }
  });
  }
});
});

Additionally, you should always encode user input if you include it in a URI. Otherwise you'll experience unexpected behaviour when using any non alphanumerical character (including whitespace) in the search box. For a more detailed explanation of how and why, see the documentation.

danzel
  • 270
  • 1
  • 7
  • Thank you so much! such a simple fix. I do have another question though. So this is a wikipedia viewer I'm making for my free code camp objective and for some reason, when I search for things that are more than 1 word, it causes an issue. If I search for computer program, it works but when I type computer programming, it comes up with no matching result. However, if I type in computer programm, computer programming comes up. – Joon Park Feb 29 '16 at 17:01
  • Just a guess: spaces and most other non-alphanumerical characters must be escaped in urls. Take a look at [this answer](http://stackoverflow.com/questions/6544564/url-encode-a-string-in-jquery-for-an-ajax-request/6544603#6544603) – danzel Feb 29 '16 at 17:15
  • I tried encodeURIComponent. looks like it's giving me the same error. when I manually type the API url into my web browser as: https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&limit=5&search=computer programming&callback=? it actually brings up the json data so I'm not really sure what I'm missing – Joon Park Feb 29 '16 at 18:50
  • updated my answer. As you can even see in your comment, the problem is the whitespace between the search terms. encodeURIComponent replaces those by %20, which your browser most likely also does when you enter the url. Note that encodeURIComponent(string) doesn't alter the string but returns (i.e. evaluates to) the encoded string. – danzel Feb 29 '16 at 19:05
  • I tried to set a new variable with encode URIComponent, this works for certain words but there are other words that it still doesn't work it. computer programming still shows no matched result and there are couple other words that just refuse to work. but it seem to work for the most part – Joon Park Feb 29 '16 at 20:08
  • I think I've found the problem. In the for loop where you iterate over the results, you set the innerHtml to "No matching results" whenever one of the results is undefined and you always execute the for loop five times. In the case of "computer programming", the JSON only contains 4 results; in the 5th iteration, `data[3][5]` is of course undefined because there is no fifth result. – danzel Feb 29 '16 at 20:44
  • *It's actually `data[3][4]' in the 5th iteration, sorry – danzel Feb 29 '16 at 21:06
  • IT WORKED!! I changed the code so that if it has less than 5 available data, it will just display the data it has and then if it doesn't have any data at all, it displays 'no matching results. Thank you so much! – Joon Park Mar 01 '16 at 20:41