Wikipedia viewer: getting more results when a button is clicked

Wikipedia viewer: getting more results when a button is clicked
0

#1

I’ve already completed my wikipedia project and am woking on a better version of this. I have written all the code but what I’d really like to do is have a “more” button which outputs the next 10 results if/when the user clicks the “more” button.

I’m really struggling with the implementation of this, specifically getting the gsroffset value from the success function of my ajax call and then passing this into the code for the button on click. I’ve tried doing this in several different ways but the gsroffset value is always undefined when i console.log it inside the function for the ‘more’ button (its the correct value inside the ajax success function). I’m guessing that this might have to do something with the asynchronous nature of the ajax call.

Has anyone managed to get a more button working? Or does anyone have any ideas about how to fix this? I’m not too sure on how to resolve this with a callback and I don’t know anything about promises.

I have been using this codepen to try and get it to work - https://codepen.io/Jennah2121/pen/ZJorwO?editors=0011

Thanks in advance :slight_smile:
Jennah


#2

I added a data attribute called “next” to the More button. I cleaned up your code and made comments below where I added new code.

var searchterm = "harry potter";

$(document).ready(function() {
  //this code works
  $("#submit").on("click", function() {
    event.preventDefault();
    getresults(searchterm);
  });

  $("#more").on("click", function(event) {
    getresults(searchterm); // added this call to get the next set of results.
  });
});

//makes a request to the api and then ouptuts the results
function getresults(searchterm) {
  var gsroffset = $("#more").data("next");
  // the above line assigns the value of the "next" data attribute which will either 
  // be blank or an offset value

  $.ajax({
    url: "https://en.wikipedia.org//w/api.php?action=query&format=json&prop=info%7Cextracts&generator=search&inprop=url&exsentences=1&exintro=1&explaintext=1&gsrsearch=" 
       + searchterm + "&gsroffset=" + gsroffset,
    dataType: "jsonp",
    success: function(result) {
      $.each(result.query.pages, function(index, value) {
          $("#results").append("<a href='"+value.fullurl+"'target='blank'><p class='dayP'><span class = 'titleText'>"+value.title+"</span><br>"+value.extract+"..</p></a>");
      });
      //How can I pass this to the button on click?
      $("#more").data("next", result.continue.gsroffset);
      // the above line assigns the offset received back from the AJAX call to the 
     // "next" data attribute to use the next time the More button is clicked.
    }
  });
}

#3

Thank you so much for your help! It works perfectly now. I had no idea about data attributes - such a simple solution. Thanks again.