user3514052
user3514052

Reputation: 429

multiple ajax response by div class

I have multiple div's where I want to show if record exist in database.

<div data-id="ca9657f6-8aa7-3645-3c14-5c59fdbc93a3" class="contact_response"></div>
<div data-id="cdffb4fb-b2c8-f2db-c056-5c560665edad" class="contact_response"></div>

I try this, but it returns only first id result everywhere

var contact_id = $('.contact_response').data("id");

$.ajax({
  "url": "http://localhost/api/check.php",
  "type": "POST",
  "contentType": "application/json",
  "data": JSON.stringify({"record_id": contact_id, "module": "contact"}),
  success: function(result)
  {
        $(".contact_response").html(result); 
  },
  error: function(result) { 
      $(".contact_response").html(result);
  }  
});

Upvotes: 0

Views: 41

Answers (2)

Pete
Pete

Reputation: 58432

I would put it in an each loop:

$('.contact_response').each(function() {
  var $thisDiv = $(this);               // get the current div
  var contact_id = $thisDiv.data("id"); // get the data id from the current div
  
  $.ajax({                               // make your ajax call
    "url": "http://localhost/api/check.php",
    "type": "POST",
    "contentType": "application/json",
    "data": JSON.stringify({
      "record_id": contact_id,
      "module": "contact"
    }),
    success: function(result) {
      $thisDiv.html(result);         // change the current div html
    },
    error: function(result) {
      $thisDiv.html(result);
    }
  });
});

Upvotes: 1

maztch
maztch

Reputation: 1697

Because the class selector return an array, you should loop over each element.

jQuery.each( $('.contact_response'), function(i, element ) {
  callCheck(element);
});

function callCheck(element){
  var contact_id = $(element).data("id");
  $.ajax({
    "url": "http://localhost/api/check.php",
    "type": "POST",
    "contentType": "application/json",
    "data": JSON.stringify({"record_id": contact_id, "module": "contact"}),
    success: function(result)
    {
        $(element).html(result); 
    },
    error: function(result) { 
      $(element).html(result);
    }  
  });
}

Upvotes: 0

Related Questions