Peanut
Peanut

Reputation: 3295

jQuery html() wont overwrite current html

Ok this is my jQuery:

$.ajax({
    type: "POST",
    url: $(this).attr('href')
}).done(function( msg ) {
    $(this).parent().closest('p').html('Image Removed');
});

This is my HTML:

<div id="gallery">
    <? foreach($galleryImages as $image) { ?>
        <div id="<?php echo $image['id'] ?>" class="box">
            <img src="<?php echo $fileHandler->get_thumb(__LISTING_GALLERY__.$image['image']) ?>" alt="Gallery Image" class="gallery-image" /><br />
            <p class="text-right"><a href="<?php echo __BASE_URL__.'/installers/dash/delete_gallery.php?id='.$image['id'] ?>" class="confirmation"><i class="fa fa-times"></i> Delete</a></p>
        </div>
    <? } ?>
</div>

The ajax works fine since the database changes and such. However, the done function isn't working properly.

I alerted the $(this).parent().closest('p').html() and it will alert the current html that div has. However, it won't overwrite it with the 'Image Removed' I'm typing in.

Upvotes: 0

Views: 70

Answers (2)

A. Wolff
A. Wolff

Reputation: 74420

Use ajax context option:

$.ajax({
    type: "POST",
    url: $(this).attr('href'),
    context:this
}).done(function( msg ) {
    $(this).parent().closest('p').html('Image Removed');
});

Upvotes: 1

adeneo
adeneo

Reputation: 318212

this inside the done function isn't the element, as there is a new function scope

var elem = this;

$.ajax({
    type: "POST",
    url: $(this).attr('href')
}).done(function( msg ) { // new function scope, "this" is now the XHR function
    $(elem).parent().closest('p').html('Image Removed');
});

Upvotes: 7

Related Questions