Update the image view when replacing it in the source folder without reloading the page

1

I have the following problem, it is a page where the products have an image, I want to change the image, replacing it in the source folder, that works for me. What does not work for me is how to update the new image (which has the same name and is in the same folder that was replaced) without reloading the page

Image code:

<a href="#" id="editImg">Cambiar imagen</a>
<label>Codigo:</label><span id="viewCodigo">PROD001</span>
<img src="images/PROD001.jpg" id="viewImg">

Modal to change image is with jquery-ui:

<div id="mdlEditImg" title="Cambiar imagen" style="display:none;">
    <form action="" role="form" enctype="multipart/form-data" id="formEditImg" name="formEditImg">
        <label for="editImagen">Elegir imagen:</label><br>
        <input type="file" name="editImagen" id="editImagen" class="archivo" accept="image/jpeg, .jpg, .png" style=""><br>
        <input type="submit" name="editar" id="submitEditImg" value="Cambiar imagen">
        <a href="#" id="editclose">Cancelar</a>
    </form>
</div>

Jquery code:

$('#mdlEditImg').dialog({
    autoOpen: false,
    modal: true,
    width: 450,
    height: 'auto',
    resizable: false,
    close: function(){
        $('#editImagen').val("");
    }
});
$('#formEditImg').submit(function(e){
    var image = $('#editImagen')[0].files[0];
    var imageName = image.name;
    var exten = imageName.substring(imageName.lastIndexOf('.') + 1);
    var datos = new FormData(document.getElementById('formEditImg'));
    datos.append("accion", "cambiarImg");
    datos.append("exten", exten);
    datos.append("codigo", $('#viewCodigo').text());
    $.ajax({
        type: "POST",
        url: "productos-ajax.php",
        data: datos,
        cache: false,
        contentType: false,
        processData: false,
        dataType: "html",
        beforeSend: function(){
        },
        error: function(){
            alert("Error en el servidor");
        },
        success: function(data){
            if (data == "true") {
                alert("Imagen cambiada correctamente!");
            } else {
                alert("Error al cambiar la imagen");
            }
        }
    });
    e.preventDefault();
});

Php code that replaces the image:

if ($_POST['accion'] == "cambiarImg") {
    $result = "";
    $carpeta = "images/";

    if (is_dir($carpeta)) {
        #Reemplazamos la imagen anterior pero con el mismo nombre que viene a ser el codigo del producto
        if (!move_uploaded_file($_FILES['editImagen']['tmp_name'], $carpeta.$_POST['codigo'].".".$exten)){
            $result = "Ocurrió algún error al subir el fichero. No pudo guardarse.";
        } else {
            $result = "true";
        }
    } else {
        $result = "no existe la carpeta";
    }

    echo $result;
}

What I want is to update the new image that I replaced without having to reload the page because the change arises after updating the page, thanks in advance and I hope you have understood me. : P

    
asked by Crisdu Salas Gutierrez 09.03.2017 в 05:23
source

2 answers

1

Extending the answer of @ A.Cedano, once the success is obtained from the backend:

success: function(data){
   var imgPath="images/"+data.nombrenuevorecibidoendata;
   $('#viewImg img').attr("src", imgPath);
   alert("Imagen cambiada correctamente!");
}

If the name of the image file is maintained (for example, because it is constructed deterministically with the slug of the product, or with its ID), modify the src attribute by

$('#viewImg img').attr("src", imgPath);

Probably would not generate a refresh in the image , whose route will already be in the browser cache .

To avoid this effect, you can add a random suffix (separated by a question mark) whose effect is harmless to bring the image, and complies with convince the browser to request its content to the server and not its cache .

For example, you can use Date.now() to get a timestamp and put:

success: function(data){
   var imgPath="images/"+data.nombrenuevorecibidoendata+"?"+Date.now();
   $('#viewImg img').attr("src", imgPath);
   alert("Imagen cambiada correctamente!");
}
    
answered by 15.03.2017 в 22:03
0

That's done in jQuery.

If the POST you make to the file productos-ajax.php succeeds (success) among the things that said PHP returns you must include the name of the new image, success receives it in variable data . Then you can take it from data and change the src attribute (imagesource) using the id that you have given to the image in the HTML, that is% viewImg :

   success: function(data){
            //Para trabajar con variables...
            var imgPath="images/"+data.nombrenuevorecibidoendata;
            $('#viewImg img').attr("src", imgPath);
            alert("Imagen cambiada correctamente!");

The logic works like this: Through jQuery you send data to the server (POST) and jQuery retrieves what the server responds in the variable data of the success function, ( success: function(data){...

attention:

  • in data there will be everything that the php says (echo, return, print_r ...) normally the php that is done POST is configured to return an array, that way you can read the values with more ease. It is not necessary to evaluate data == "true" within the success
  • The PHP file you use in jQuery is an auxiliary file, not the same as the page from which you sent the request to jQuery. This is what allows the current page to be updated without having to load it again.
  • answered by 09.03.2017 в 05:53