Ryan D Ryan D - 1 month ago 19
PHP Question

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?

Answer

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  +'"/>' );
  });
}