Ryan D
Ryan D

Reputation: 751

Refresh image after its been replacedWith image using jQuery PHP

I am using simpleImage, a php image manipulation library.. I am trying to rotate the image externally using ajax and replaceWith. It replaces the image and everything but it wont refresh when rotated..

index.php -

//Submit Form
function subForm() {
event.preventDefault();
var name = $('#target').val();
console.log(name);
$.post("rotate.php", {name: name},
function(data) {
$("#preview").replaceWith( '<img id="replace" src="'+data+'"/>' );
});
}



<img src="'.$target.'" id="preview"/>

<form method="post" action='' id="rotateForm" data-ajax="false">
<input type="submit" id="rotate"  onclick="subForm();" value="rotate">
</form>

** UPDATED**

rotate.php -

$time = time();
$newImg = $_POST['name'];
$img = new abeautifulsite\SimpleImage($newImg);
$img->rotate(90)->best_fit(500, 500)->save();
echo $newImg.'?'.$time;

The image rotates but doesn't update on the page with out the page being reloaded.. Am I using the wrong approach here?

Upvotes: 1

Views: 814

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206343

Images do usually get cached by the browser.

The problem:

  1. you show some image with a specific src like someimage.jpg
  2. You rotate that image and provide it with the same src someimage.jpg
  3. the browser will load the old one from the cache!

To prevent that you could simply request a brand new one using a timestamp like

someimage.jpg?t=1476400456961

and the browser will load a clean someimage.jpg from the server.


A JS solution is:

function subForm() {

  event.preventDefault();

  var name = $('#target').val();
  console.log(name);

  $.post("rotate.php", {name: name}, function(data) {
    var tStamp = +new Date(); // Generate always a new timestamp milliseconds value
    $("#preview").replaceWith( '<img id="replace" src="'+ data+"?t="+ tStamp  +'"/>' );
  });
}

Upvotes: 1

FrenchTechLead
FrenchTechLead

Reputation: 1156

You have rewrite the src attribute of your tag so that the image loads again.

Upvotes: 1

Related Questions