marcelps
marcelps

Reputation: 319

Change src images after ajax call

In an admin web page, I have a list with many items, and in each item there is a button that allow show or hide those items for final users. When the item is showing, the button is an image with an opened eye. And when the image is hiding, the button is an image with closed eye. How it works? For example, in an hidden item, the button is an image with eye closed. So, when I click in the button to show de item, the item will be show for users, and the image changes for opened eye.

I'm using ajax+jquery for this.

The problem is when I click in the button to show or hide an item, the image and his attributes doesn't change! The ajax is working, but the image button doesn't change.

Ajax:

$(document).on('click', '#UpdatePreview', function(e){

    e.preventDefault();

    var uid = $(this).attr('name');
    var eye = $(this).children('#imgEye').attr('name');

    $.ajax({
        url: 'previewLeiame.php',
        type: 'POST',
        data: {id: uid},
        dataType: 'html',
        success: function(data) {
            if(eye == "visualized") {
                $(this).children('#imgEye').attr('src', '../imgs/btn/no-eye-icon.png');
                $(this).children('#imgEye').attr('name', 'hidden');
                $(this).children('#imgEye').attr('title', 'Hidden');
            } else if(eye == "hidden") {
                $(this).children('#imgEye').attr('src', '../imgs/btn/eye-icon.png');
                $(this).children('#imgEye').attr('name', 'visualized');
                $(this).children('#imgEye').attr('title', 'Visualized');
            }
        }
    });

});

HTML:

<td width="35" align="center">
    <?php
        if($data['preview'] == 0) {
    ?>
            <a id="UpdatePreview" name="<?php echo $data['id']; ?>"><img id="imgEye" name="hidden" title="Hidden" src="../imgs/btn/no-eye-icon.png" /></a>
    <?php
        } else { ?>
            <a id="UpdatePreview" name="<?php echo $data['id']; ?>"><img id="imgEye" name="visualized" title="Visualized" src="../imgs/btn/eye-icon.png" /></a>
    <?php }
        ?>
</td>

Can anybody help me ? Thank you!

Upvotes: 0

Views: 721

Answers (1)

Felix Kling
Felix Kling

Reputation: 816334

this inside the success callback does not refer to the DOM element, so $(this).children('#imgEye') will simply be empty.

It would be much simpler if you stored a reference to the element outside the Ajax call.

var img = $(this).children('#imgEye');

$.ajax({
  // ...
  success: function() {
    // ...
    img.attr(...);
  }.
});

If you really want this to refer to the DOM element, see $(this) inside of AJAX success not working .

Upvotes: 2

Related Questions