How to update the child div element on ajax success in php

Viewed 45

I want to update the child div but all the divs are getting updated on ajax success.

My html

<div class="add_wishlist">
<input type="hidden" name="prd_wishlist" class="prd_wishlist" value="1">
     <div class="wishlist_icon">
       <p><i class="far fa-heart"></i></p>
     </div>
</div>
<div class="add_wishlist">
<input type="hidden" name="prd_wishlist" class="prd_wishlist" value="2">
     <div class="wishlist_icon">
       <p><i class="far fa-heart"></i></p>
     </div>
</div>

Jquery

$('.add_wishlist').click(function(){

var prd_wish = $(this).find("[name='prd_wishlist']").val()

$.ajax({
    type: 'post',
    url: weburl+'pages/login-script.php',
    data: {
        prd_wish:prd_wish,
        wishlist_submit:'submit',
    },
    success: function (response) {
        
        $('.add_wishlist').children('.wishlist_icon').html(response)
    }
});
})

I also tried to update the code with $('.add_wishlist').children('.wishlist_icon').html(response) but its not working.

1 Answers

Store a reference to the clicked .add_wishlist element in the click handler, then use that within the success handler:

$('.add_wishlist').click(function() {
  let $addWishlist = $(this);
  let prd_wish = $addWishlist.find("[name='prd_wishlist']").val()

  $.ajax({
    type: 'post',
    url: weburl + 'pages/login-script.php',
    data: {
      prd_wish: prd_wish,
      wishlist_submit: 'submit',
    },
    success: function(response) {
      $addWishlist.children('.wishlist_icon').html(response);
    }
  });
})
Related