0

I work with the api new york times search engine, my question is simple, i just want to change parameters in my url using a input type text in my html. How can i do that ? End date and sort are one of the parameter, i just want to know how can i change the string with an input field in html. here a copy of my code :

html :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <link rel='stylesheet' type="text/css" href="nyt.css">
    <link rel='stylesheet' type="text/css" href="font.css">
    <link rel='stylesheet' type="text/css" href="grille.css">
</head>
<body>
    <div class='container'>
       <button type="submit" id='searchButton'></button>
       <input type="text" id='searchTerm' placeholder="search">
    </div>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src='nyt.js'></script>
</body>
</html>

js :

var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
var searchTerm = document.getElementById('searchButton');
url += '?' + $.param({
  'api-key': "[API KEY]",
  'end_date': "19440606",
  'sort': "newest"
});
$.ajax({
  url: url,
  method: 'GET',
  q: searchTerm,
}).done(function(result) {
  console.log(result);
}).fail(function(err) {
  throw err;
});
Chalom.E
  • 617
  • 5
  • 20

2 Answers2

0

You can get the value of your input field with the “value” property, like so:

var searchTerm = document.getElementById('searchButton').value;

See also: JavaScript: how to get value of text input field?

Community
  • 1
  • 1
Patrick Hund
  • 19,163
  • 11
  • 66
  • 95
0
function sendRequest(searchTerm) {
  var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
  url += '?' + $.param({
    'api-key': "[API KEY]",
    'end_date': "19440606",
    'sort': "newest"
  });
  console.log(searchTerm);
  return $.ajax({
    url: url,
    method: 'GET',
    q: searchTerm,
  });
}

document.querySelector('#searchButton').addEventListener('click', function(e){
  e.preventDefault();
  var query = document.querySelector('#searchTerm').value.trim();

  if (query.length > 0) {
    sendRequest(query)
      .done(function(result) {
        console.log(result);
      }).fail(function(err) {
        throw err;
      });
  }
})
caisah
  • 1,959
  • 1
  • 21
  • 31