getJSON, Changing the api call url variable before the call

629 Views Asked by At

I'm trying to use a simple API that displays information about countries. In the var apiCall I can hardcode a country at the end of the url and the getJSON method works as intended and displays the information.

var apiCall = "https://restcountries.eu/rest/v1/name/england";

$.getJSON(apiCall, function(data){

 $("#country").html("Country Name: " + data[0].name + " - " + data[0].alpha2Code);

  $("#capital").html("Capital: " + data[0].capital);

  $("#region").html("Region: " + data[0].region + " - " + data[0].subregion);

  ...

I want to add the country name afterwards, with user input:

HTML:

<input type="text" placeholder="Country Name" id="inputText"></input>
<button id ="searchButton"> Search </button>

JS

var inputText = $("#inputText");
var apiCall = "https://restcountries.eu/rest/v1/name/";


$("#searchButton").click(function(){
  return apiCall = apiCall + inputText.val();
});

If instead of return I do a console.log, I get a string like the one that works at the beginning, if the user type "england", then I get "https://restcountries.eu/rest/v1/name/england"

$.getJSON(apiCall, function(data){

 $("#country").html("Country Name: " + data[0].name + " - " + data[0].alpha2Code);

  $("#capital").html("Capital: " + data[0].capital);

  $("#region").html("Region: " + data[0].region + " - " + data[0].subregion);

   ...

What can I do so the $("#searchButton").click(function(){} actually changes the value of the apiCall and makes the getJSON run again with that new value?

2

There are 2 best solutions below

0
On BEST ANSWER

This should work

$("#searchButton").click(function(){
  apiCall = apiCall + inputText.val();
  $.getJSON(apiCall, function(data){ ... });
});
0
On

My recommendatation is to refactor the API acall into its own function like this:

 function refreshCountryDetails (country) {
     var url = (apiCall + country);
     $.getJSON(url, function(data) {
         $("#country").html("Country Na......});
     }
  }

Then when a user clicks the searchButton, we just call our API wrapper to get the country details with the user's input (inputText.val()):

  $("#searchButton").click(function(){
      refreshCountryDetails(inputText.val());
  });