Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

93
Views
Api call doesn't jQuery / javascript

I am trying use the pokeApi for a site but my function doesn't work the second time.

The result in next = the next link I want to use that the Api returns.

const beginLink = "https://pokeapi.co/api/v2/pokemon/";
let next;
let previous;
apiCall(beginLink);

function apiCall(link) {
  $('#pokemons').html(``);
  $.ajax({
    url: link
  }).done(handleResponse);
  
  function handleResponse(data) {
    next = data.next;
    previous = data.previous;
    for (let i = 0; i < 20; i++) {
      $('#pokemons').append(`<div class="pokemon"><img src="https://raw.githubusercontent.com/msikma/pokesprite/master/pokemon-gen8/regular/${data.results[i].name}.png"><br><p>${data.results[i].name}</p></div>`);
    }
  }
}

$("#next").on("click ", apiCall(next));
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The main issue is because apiCall(next) doesn't return a function. Therefore, when the click event occurs nothing happens.

To fix this issue, and also to remove the reliance on global variables which should avoided, you can place the URL of the next call in to the data held by the #next element. This way the function which updates the content of the DOM based on the AJAX response is entirely self-contained.

let $next = $('#next');
let $pokemonContainer = $('#pokemons');

function apiCall() {
  $pokemonContainer.empty();
  $.get($next.data('url')).done(handlePokemonApiResponse);
}

function handlePokemonApiResponse(data) {
  $next.data('url', data.next);
  let html = data.results.map(p => `<div class="pokemon"><img src="https://raw.githubusercontent.com/msikma/pokesprite/master/pokemon-gen8/regular/${p.name}.png"><br><p>${p.name}</p></div>`);
  $pokemonContainer.html(html);
}

$next.on("click", apiCall).trigger('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<button type="button" id="next" data-url="https://pokeapi.co/api/v2/pokemon/">Next</button>
<div id="pokemons"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!