Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

95
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda