Scott
Scott

Reputation: 1247

Page is refreshing on JSON request

I am trying to build a page that would allow a user to input text into a text field and hit enter on their keyboard and it would return the top 10 Wikipedia entries with that text.

Currently, my concern is that the page refreshes every time it fetches the JSON. I attempted the e.preventDefault() method, as I read about on other questions, but it isn't working. Can someone help me understand why this auto-refresh is happening, and how to fix it? Thank you.

Here is my HTML:

<div class="container-fluid">
  <form action="#">
    <input id="search" name="query" onkeyup="" type="text"></input>
  </form>
</div>
<div class="main"></div>
</div>

And here is my Javascript:

$(document).ready(function() {
  $("#search").on("keyup", function(e) {

    // attempt to prevent page refresh
    e.preventDefault();

    // if key pressed is "enter"
    if (e.keyCode == 13) {

      // retrieve user input
      var search = document.getElementById("search").value;

      // build Wikipedia API url
      var request = "https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=" + search + "&format=json&callback=?";

      $.getJSON(request, function(json) {
      var x = json.query.search[0]["snippet"];
      $(".main").html(x);
      });
    };
  });
});

Here's a link: https://codepen.io/lieberscott/pen/RLVaGE

Upvotes: 0

Views: 78

Answers (3)

brk
brk

Reputation: 50326

You are using a form and on enter/return it will try to submit the form.

Unless there is a button type="submit" or input type='submit' remove the form and use only input

<div class="container-fluid">
 <input id="search" name="query" onkeyup="" type="text"></input>
</div>
<div class="main"></div>
</div>

Upvotes: 0

ishan shah
ishan shah

Reputation: 603

Remove <form> tag from your HTML.

Upvotes: 0

Martijn
Martijn

Reputation: 16123

Because you submit the form (pressing enter does that). The form submits to the current page which looks like a reload.

<form id="searchform>
    <input id="search" name="query" onkeyup="" type="text"></input>
  </form>

$('#searchform').on('submit', function(e){
    e.preventDefault();
    // your magic here.
});

The preventDefault stops the key UP, but by that time, you've already started submitting. The poreventDefault stops the enter getting input as text (you can check this with a textarea). If you'd change it to a letter, say A, you'd type the A, but not see it.

You can also remove the form itself, keeping just the input, if that doesnt create other issues, resulting in less HTML, which is nice.

Upvotes: 1

Related Questions