This is my jQuery to add/remove from a wish list. I echo added/add to wish list and receive response.
The PHP part is fine, my problem is that the class name is the same for displaying the wish list in all products so innerHtml changes in every product on execution. Each product has a unique id though.
How can I change the wish list icon of only clicked div?
$(document).on('click', '.addingwish', function() {
var product_id = $(this).attr("id");
var email = "<?php echo $_SESSION['username']?>";
$.ajax({
url: "actionadd.php",
method: "POST",
data: {
product_id: product_id,
email: email
},
success: function(data) {
$('.addingwish').html('');
$('.addingwish').html(data);
}
})
});
>Solution :
Assuming I’ve understood your question, you want to target the clicked element when setting the html() from the response of the AJAX request.
To do that store a reference to the clicked element in the event handler, using the this keyword, and use that when calling html():
$(document).on('click', '.addingwish', function() {
let $el = $(this);
$.ajax({
url: "actionadd.php",
method: "POST",
data: {
product_id: $el.prop('id'),
email: '<?php echo $_SESSION['username']?>'
},
success: function(data) {
$el.html(data);
}
})
});
Note that you don’t need to call html('') to clear the existing content as it’s overwritten when setting the new content.