user3733831 user3733831 - 1 month ago 7
Ajax Question

How I fix this jquery / ajax issue?

Basically I am having a table like below:

<tbody>
<tr>
<td><img class="img-thumbnail" src="./images/no_image.png" width="100" height="100"></td>
<td><button class="change_image" data-image_id="1">Change Image</button></td>
<td><input type="text" name="sort[]" size="7" placeholder="Sort order"></td>
</tr>
<tr>
<td><img class="img-thumbnail" src="./images/no_image.png" width="100" height="100"></td>
<td><button class="change_image" data-image_id="2">Change Image</button></td>
<td><input type="text" name="sort[]" size="7" placeholder="Sort order"></td>
</tr>
<tr>
<td><img class="img-thumbnail" src="./images/no_image.png" width="100" height="100"></td>
<td><button class="change_image" data-image_id="3">Change Image</button></td>
<td><input type="text" name="sort[]" size="7" placeholder="Sort order"></td>
</tr>
</tbody>


When click on
.change_image
button, its opening a modal to change that image.

This is how my modal open:

$('#manage_images').on('click', '.change_image', function(){
window.tr = $(this).parents('tr');
var image_id = $(this).data("image_id")

$('#chage_pro_image_form')
.find('[name="image_id"]').val(image_id).end();

$("#modal").modal({
"backdrop" : "static",
"keyboard" : true,
"show" : true
});
});


Next thing is I want to submit form (which is in the modal) to change this image. I did it correctly using
jquery/ajax


Now I want to replace old image with newly change image on this table row after ajax success.

This is how I tried it in
ajax
success function:

success: function(json) {
var json = JSON.parse(json);
if (json.success) {
$('#modal.modal').modal('hide');
$('#chage_pro_image_form').formValidation('resetForm', true);

d = new Date();
window.tr.find('img').fadeOut(1000, function() {
$("img").attr("src", json.image+"?"+d.getTime());
}).fadeIn(1000);
} else {
// my errors
}
}


My problem is, its replacing all existing images in the table with new one. I created a global variable
window.tr
. But it doesn't work for me.

Can anybody help me to figure this out?
Thank you.

Answer

Use this to reference the image instance inside the animation callback

window.tr.find('img').fadeOut(1000, function() {
      $(this).attr("src", json.image+"?"+d.getTime());
}).fadeIn(1000);