Nebojsa Sapic
Nebojsa Sapic

Reputation: 89

update image after ajax call

I have some problems.

On click I rotate image with ajax and save new image. Everything is without page refresh. And problem is that old image won't refresh and put new refreshed image.

Also new image have same name like the old one.

QUESTION

My question is how to update img from folder without page refresh? Only after click class slika-rotiraj.

HTML :

<div class="slika">
    <div class="slika-obrisi"></div>
    <div class="slika-rotiraj"></div>
    <img src="uploads/87b6f334f30717343acd69f3962142a0_542ad975e424d.jpg" />
</div>

SCRIPT :

$(document).on("click", ".slika-rotiraj", function() {
    var slika = $(this).next("img").attr("src");
    var slika1 = $(this).parent();
    var slika2 = $(this).next("img");
    $(this).next("img").attr("src", slika);
    $.ajax({
        type: "POST",
        url: "rotiraj.php",
        data: {
            slika: slika
        },
        success: function(data) {

        }
    });
});

Upvotes: 5

Views: 15228

Answers (3)

Ragnar
Ragnar

Reputation: 4578

Try something like this if the image has always the same name:

$('.slika img').attr('src', 'new path to image');

otherwise:

$('.slika img').attr('src', 'new path to image' + '?_=' + new Date().getTime()); 

Upvotes: 0

thiag0
thiag0

Reputation: 2229

Give your tag an id and set the value of the 'src' attribute inside your success function of the ajax call.

HTML

<div class="slika">
    <div class="slika-obrisi"></div>
    <div class="slika-rotiraj"></div>
    <img id="myimage" src="uploads/87b6f334f30717343acd69f3962142a0_542ad975e424d.jpg" />
</div>

JS:

$(document).on("click", ".slika-rotiraj", function() {
    var slika = $(this).next("img").attr("src");
    var slika1 = $(this).parent();
    var slika2 = $(this).next("img");
    $(this).next("img").attr("src", slika);
    $.ajax({
        type: "POST",
        url: "rotiraj.php",
        data: {
            slika: slika
        },
        success: function(data) {
            $("#myimage").attr('src', data);
        }
    });
});

Upvotes: 1

David
David

Reputation: 218818

Do you mean that the image has changed server-side and you just want to force the img tag to fetch the new state of the image? Simply setting the src should accomplish that:

success: function(data) {
    // which is your image?  "slika2"?
    // it's not really obvious, so I'll assume that for now
    $(slika2).attr('src', slika);
}

If this isn't refreshing the image, you might add a "cache-breaker" to force it to re-request. Something as simple as this:

success: function(data) {
    $(slika2).attr('src', slika + '?' + new Date().getTime());
}

This wouldn't affect anything, it would just innocuously change the URL and force the browser to re-request from the server.

Upvotes: 7

Related Questions