简体   繁体   中英

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.

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);

Well obviously the $("img") selector will select all img elements. You need to somewhere store which button you changed as a variable. For instance by pointing to the data-image_id attribute. Then you can select it using:

 $('[data-image_id='+image_id+']') 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM