Wiki API search project

Hi, I’m getting really confusing results from my code - sometimes it console.logs the wiki api json just okay and sometimes it just doesn’t. Without any change in the code!
Any idea on what’s going on?

$(document).ready( function() {
$(’#search_btn’).click(function() {
var query = $("#query").val();
var link = “https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=” + encodeURIComponent(query) + “&callback=?”;
console.log(link);
$.ajax({
type: “GET”,
url: link,
dataType: ‘jsonp’,
success: function(data) {
console.log(data);
}
});

});
$(’#query’).keypress(function(e){
if(e.which == 13){//Enter key pressed
$(’#search_btn’).click();//Trigger search button click event
}
});
});

<a href="https://en.wikipedia.org/wiki/Special:Random" target="_blank"
   <h1>Random article</h1></a>
<form>
  <input type="text" name="query" id="query"><br>
</form>
<h1 id="search_btn">search</h1>
<p>---</p>

Post the HTML part of the code.

Thanks jenovs! edited the initial post.

HTML forms have default action to refresh a page when you submit them (in your case when you press enter). You should prevent this default action.

$('#query').keypress(function(e) {
    if (e.which == 13) { //Enter key pressed
      e.preventDefault(); // <--- ADD THIS
      $('#search_btn').click(); //Trigger search button click event
    }

But you can add button with type ‘submit’ to your form and get rid of .keypress:

HTML:

<form>
  <input type="text" name="query" id="query"><br>
  <button type="submit">Search</button>
</form>

JS:

$(document).ready(function() {
  $('form').on('submit', function(e) {
    e.preventDefault();
    var q = $("#query");
    var query = q.val();
    var link = "https://en.wikipedia.org/w/api.php?action=opensearch&format=json&search=" + encodeURIComponent(query) + "&callback=?";
    console.log(link);
    $.ajax({
      type: "GET",
      url: link,
      dataType: 'jsonp',
      success: function(data) {
        q.val('');
        console.log(data);
      }
    });
  });
});
1 Like

Thanks a lot, I was really getting desperate.

Here is an explanation I made for my High School Students. It might clarify a few things as well.

1 Like

Not OP but having same issue. Thank you for this!