AJAX query does not have correct reference to variable

This is my code:

$('.store-card').each(function() {
  placeid = $(this).data('placeid');
  latlng = $(this).data('latlng');

  card = this;
  console.log("1 ", card);

  $.ajax({
    url: '/stores/placeid/',
    method: "GET",
    data: {
      placeid: placeid
    },
    dataType: 'json',
    success: function(response) {
      console.log(card);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The problem here is that by the time the AJAX queries return a response, the refernce to card has already changed, hence card will always have the value of the last item.

This the console output:

    1  <div class="store-card" data-map="#slink-10" data-timing="#stmg-10" data-openhours="#sopen-10" data-placeid="ChIJTZD7ufceDTkRXZdMW4ObIM4" data-latlng="">
    1  <div class="store-card" data-map="#slink-9" data-timing="#stmg-9" data-openhours="#sopen-9" data-placeid="ChIJK-bJgRwDDTkR5vzdTwSc7JI" data-latlng="">
    1  <div class="store-card" data-map="#slink-22" data-timing="#stmg-22" data-openhours="#sopen-22" data-placeid="ChIJk2W43rPjDDkRMeRmDOo8QT8" data-latlng="">
    1  <div class="store-card" data-map="#slink-11" data-timing="#stmg-11" data-openhours="#sopen-11" data-placeid="ChIJebql01D7DDkRMELWwmmpS_A" data-latlng="">
    <div class="store-card" data-map="#slink-11" data-timing="#stmg-11" data-openhours="#sopen-11" data-placeid="ChIJebql01D7DDkRMELWwmmpS_A" data-latlng="">
    <div class="store-card" data-map="#slink-11" data-timing="#stmg-11" data-openhours="#sopen-11" data-placeid="ChIJebql01D7DDkRMELWwmmpS_A" data-latlng="">
    <div class="store-card" data-map="#slink-11" data-timing="#stmg-11" data-openhours="#sopen-11" data-placeid="ChIJebql01D7DDkRMELWwmmpS_A" data-latlng="">
    <div class="store-card" data-map="#slink-11" data-timing="#stmg-11" data-openhours="#sopen-11" data-placeid="ChIJebql01D7DDkRMELWwmmpS_A" data-latlng="">

How can I ensure that each $.ajax will have the corresponding reference to card rather than the latest reference?

Answers 1

  • You must not forget to add var to all first time declared variables!

    So try change code to this:

    var placeid = $(this).data('placeid');
    var latlng = $(this).data('latlng');
    
    var card = this;
    

Related Articles