I am trying to use a dynamically updated data attribute with jQuery.
When I first click the button the clientPrefID grabs the correct data. In my ajax call, I return the next preference id and I update the data in the success function so that I can do the same thing with a different set of data. When I inspect element on the page I can see that the the data-client-pref-id correctly updates. However, when I click the button next, the clientPrefID is still the old value! See below that I alert the value to check that this is the issue.
Here is the javascript:
$(document).on('click', '.pref-btn', function(e) {
var clientPrefID = $(this).data('client-pref-id');
var score = $(this).data('score');
// see if clientPrefID is correct value
alert(clientPrefID);
$.ajax({
type: 'POST',
url: '/portal/includes/ajax_portal.php',
dataType: 'json',
data: {
theAction: "updatePreferenceScore",
clientPrefID: clientPrefID,
score: score
},
success: function(data) {
if (data.error == undefined) {
//if the data did not return errors,
//update the item name and image and preference id
$('#item-name').html(data.plu_commodity_name);
$('#item-img').html("<img src=\"../images/item_images/plu_items/" + data.ifps_image_source + "\" height='100px'>");
$('.pref-btn').each(function() {
$(this).attr("data-client-pref-id", data.client_pref_id);
});
} else {
console.log(data.error)
}
}
})
});
And here is the html
<div class="row my-3 text-center">
<div class="col-4">
<div class="card mx-2 py-3 pref-btn pointer" data-score="2" data-client-pref-id="<?php echo $next_pref_plu['client_pref_id']; ?>">
<div class="card-body">
<h5>NO</h5>
<img src="../images/x.png" height="75px">
</div>
</div>
</div>
<div class="col-4">
<div class="card mx-2" style="border:none">
<div class="card-body">
<h4 id="item-name"><?php echo $next_pref_plu['plu_commodity_name']; ?></h4>
<div id="item-img"><img src="../images/item_images/plu_items/<?php echo $next_pref_plu['ifps_image_source']; ?>" height="100px"></div>
</div>
</div>
</div>
<div class="col-4">
<div class="card mx-2 py-3 pref-btn pointer" data-score="1" data-client-pref-id="<?php echo $next_pref_plu['client_pref_id']; ?>">
<div class="card-body">
<h5>YES</h5>
<img src="../images/check.png" height="75px">
</div>
</div>
</div>
</div>