Shubham Shukla Shubham Shukla - 6 months ago 15
Javascript Question

I am wikipedia api call ,page is automatically reloaded after jquery ajax call.page content is displayed and then reloaded

i am jquery making api call by clicking button for searching article on wikipedia.ajax works fine and content is also displayed and then reloaded.and displayed content is gone.

<h1>Wikipedia Viewer</h1>
<form class="form-inline">
<div class="container">
<div class="row">
<div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
<div class="form-group">
<label class="sr-only" for="search">search</label>
<input type="text" class="form-control" placeholder="Search">
</div>
<button type="submit" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
<a href="https://en.wikipedia.org/wiki/Special:Random">Surprise me!</a>
$(document).ready(function() {
$("button").click(function() {
var article = $("input").val(); //extract value from input box
$.ajax({ //wikipedia api call
url: "https://en.wikipedia.org/w/api.php? action=query&list=search&srsearch=" + article + "&format=json",
dataType: "jsonp",
success: function(data) {
for (var i = 0; i < data.query.search.length; i++) { //looping through json
var title = data.query.search[i].title; //adding data on page
var snippet = data.query.search[i].snippet;
$("button").append("<p>" + title + "</p>");
$("p").append("<p>" + snippet + "</p>");
}
},
error: function() {
$("h1").html("oops");
}
});
});
});
here is my codepen link
[1]: https://codepen.io/shubhamshukla1994/pen/YqgLXW

Answer

Just change your button element from type="submit" to type="button". Updated https://codepen.io/anon/pen/Yqgoyg

<h1>Wikipedia Viewer</h1>
<form class="form-inline">
  <div class="container">
    <div class="row">
      <div class="col-sm-6 col-sm-offset-4 col-lg-7 col-lg-offset-4">
        <div class="form-group">
          <label class="sr-only" for="search">search</label>
          <input type="text" class="form-control" placeholder="Search">
        </div>
        <button type="button" class="btn btn-primary"><i class="fa fa-search"></i></button></form>
</div>
</div>
</div>
<a href="https://en.wikipedia.org/wiki/Special:Random">Surprise me!</a>