8.9 New York Times API and user input...how to auto-refresh every time a new variable is queried?

Hello. I'm using Brackets to work on this code, the instruction video is outdated. I'm attempting to use my own API to do exactly what happens in the video.

The video:

Here's index.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">

    <script async src=http://CDN.JSDelivr.net/g/p5.js(p5.min.js+addons/p5.dom.js)></script>

<script defer src=sketch.js></script>

  </head>
  <body>
  </body>
</html>

And here's sketch.js:

var url = "https://"+"api.nytimes.com/svc/search/v2/articlesearch.json?q=awesome&api-key=b8c1f64df33b4dc5bb885a06f7402a20";

function setup() {
noCanvas();
loadJSON(url, gotData);
}

function gotData(data) {
//console.log(data.response.docs[1].headline.main);
    var articles = data.response.docs;
    for(i = 0; i < articles.length; i++) {
        createP(articles[i].headline.main);
    }
}

It seems that there have been some major changes that I'm unaware of and don't understand to the API. Either that or I'm using the wrong library. Thanks for giving it a look, cheers!

Answers

  • If you post your API request in a web browser, you can see it woks.

    Kf

  • Indeed it does. I have a new question regarding this code, actually. Using the same code as listed above, how can I get the query to reset every time I search using a new variable? As of now it will continue to populate the list and never reset/ erase what's already there (unless I manually refresh the page).

  • Answer ✓

    Here is a sample: http://p5js.sketchpad.cc/sp/pad/view/Kvlmcx5Tc0/latest

    Kf

    var URL1 = "https://"+"api.nytimes.com/svc/search/v2/articlesearch.json?q="
      var req="awesome"
      var URL3="&api-key=b8c1f64df33b4dc5bb885a06f7402a20";
    
    var inp;
    var bt;
    
    function setup() {
      noCanvas();
      inp = createInput('');
      bt= createButton('click me');
      bt.mousePressed(updateAndSend);
      loadJSON(URL1+req+URL3, gotData);
    }
    
    
    function updateAndSend() {
      req=inp.value();
      loadJSON(URL1+req+URL3, gotData);
      inp.value('');
    }
    
    
    function gotData(data) {
      //console.log(data.response.docs[1].headline.main);
    
      var allPs= selectAll('.mypar');
      for (var i = allPs.length-1; i >=0; i--) {
        allPs[i].remove();
      }
    
      var articles = data.response.docs;
      for (i = 0; i < articles.length; i++) {
        createP(articles[i].headline.main).addClass('mypar');
      }
    }
    
  • edited May 2017

    I'll unpack this after work, thanks. Impressive that you knew what I was talking about even though I forgot to supply my updated program ;)

    Edit: Thanks, kfrajer. The answer contains some code that I'm unfamiliar with. It works just fine!

Sign In or Register to comment.