How to reload a img attr "src" after ajax call without knowing the file name from the image tag?

Viewed 887

I have this html:

<div class="d-inline-flex">
    <img id="reloadIMG" class="p-3 mt-5 imgP" onDragStart="return false" <?php echo htmlentities($avatar, \ENT_QUOTES, 'UTF-8', false); ?>> 
    <input type="file" id="uploadAvatar" name="uploadedAvatar"> 
</div>

the value of $avatar:

$pathFolderAvatar = 'user/'.$folder.'/avatar/*';
$imgUserPastaAvatar = glob($pathFolderAvatar)[0] ?? NULL;
if(file_exists($imgUserPastaAvatar)){
    $avatar = 'src='.$siteURL.'/'.$imgUserPastaAvatar;
}else{
    $avatar = 'src='.$siteURL.'/img/avatar/'.$imgPF.'.jpg';
}

and the script to send a ajax call to my file that process the file upload request:

$(function () {
    var form;
    $('#uploadAvatar').change(function (event) {
        form = new FormData();
        form.append('uploadedAvatar', event.target.files[0]);
    });
    $("#uploadAvatar").change(function() { 
      $("#loadingIMG").show();
      var imgEditATTR = $("div.imgP").next().attr("src");
      var imgEdit = $("div.imgP").next();
      $.ajax({
          url: 'http://example/test/profileForm.php',
          data: form,
          processData: false,
          contentType: false,
          type: 'POST',
          success: function (data) {
            $("#loadingIMG").hide();
            $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime());
          }
      });
    });
});

i tried to force the browser to reload the img on success ajax call $(imgEdit).attr('src', imgEditATTR + '?' + new Date().getTime()); but the selector from the var imgEdit and imgEditATTR is not working:

console.log(imgEdit); result: w.fn.init [prevObject: w.fn.init(0)] console.log(imgEdit); result: undefined;

Why is it happening, and how to fix?

I know that there's a bunch of questions about reload img, but on these questions there's not a method to reload a image without knowing the file name. I checked so many questions and this is what the answears say:

d = new Date();
$("#myimg").attr("src", "/myimg.jpg?"+d.getTime());

On my case i don't know the file name, because it's generated randomly on profileForm.php with mt_rand():

$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;
//example of the result: 9081341_1546973622.jpg

move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
2 Answers

You can return file name in response to your AJAX request and use it in success block to update src attribute of img tag

So your profileForm.php will look something like



 $ext = explode('.',$_FILES['uploadedIMG']['name']);
    $extension = $ext[1];
    $newname = mt_rand(10000, 10000000).'_'.time();
    $folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'.'.$extension;
    //example of the result: 9081341_1546973622.jpg
    move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);
    echo $newname // you can also send a JSON object here
    // this can be either echo or return depending on how you call the function

and your AJAX code will look like



$.ajax({
      url: 'http://example/test/profileForm.php',
      data: form,
      processData: false,
      contentType: false,
      type: 'POST',
      success: function (data) {
        $("#loadingIMG").hide();
        $(imgEdit).attr('src', data);
      }
  });

Let profileForm.php return the generated filename:

$ext = explode('.',$_FILES['uploadedIMG']['name']);
$extension = $ext[1];
$newname = mt_rand(10000, 10000000);
$folderPFFetchFILE = $folderPFFetch.'avatar/'.$newname.'_'.time().'.'.$extension;

move_uploaded_file($_FILES['uploadedAvatar']['tmp_name'], $folderPFFetchFILE);

echo json_encode(['filename' => $folderPFFetchFILE]);

Then in the callback of your POST request:

success: function (data) {
  $("#loadingIMG").hide();
  $(imgEdit).attr('src', data.filename);
}
Related