1

I'm using NewYorkTimes API that gets the search query from the input field, however, when I press enter after typing the input, my localhost reloads and navigate to localhost:3000/?

I console.log(url) in the console and the url is correct as the JSON request returns results, but the results aren't displayed in HTML since the page navigates automatically. Not sure what may be causing this to happen.

form
   span.material-icons search
   input.form-control(id="input", placeholder="Search for articles, headlines, etc.")

// SHOWS SEARCH RESULTS WHEN THE USER PRESSES ENTER
$("#input").keypress(function(event) {
    if (event.keyCode == 13) {
        searchArticles(this.value);
        $("#input").val("");     
    }
});

// MAKES THE REQUEST AND DISPLAYS THE NEWS BASED ON RESULTS
function searchArticles(term) {
    term = term.replace(" ", "+");
    searchURL = "http://api.nytimes.com/svc/search/v2/articlesearch.json?q=" + term + "&api-key=" + searchAPI;
    console.log(searchURL);
    $.getJSON(searchURL, function(api) {
        api.response.docs.forEach(function(data) {
            link = data.url;
            cardTitle = data.headline;
            postedBy = data.byline.original;
            createCardElements();
        });
    });
}

This is the sample JSON request:

http://api.nytimes.com/svc/search/v2/articlesearch.json?q=new+york+times&page=2&sort=oldest&api-key=sample-key

narulakeshav
  • 141
  • 3
  • 14

1 Answers1

3

This is most likely because you are not calling event.preventDefault() in the callback for the keypress event and therefore the form is getting submitted.

The default action taken when pressing enter on an input field is often to submit the form containing that field (though it seems like this may be browser dependent). Calling event.preventDefault() stops whatever the default action is from occurring, allowing your code to run without interference.

Returning false from the callback function has a similar, but not identical, effect.