How to swap an image with Javascript

0

I need to change an image by javaScript but I'm not getting it, I tried the following way and it did not work;

html

<img id="imagemPerfil" src="img/user1.png" alt="profile image"  class="circle z-depth-2 responsive-img activator gradient-45deg-light-blue-cyan gradient-shadow">

JavaScript

document.getElementById("imagemPerfil").src ="<?php echo'../img/perfilUsuario/'.$usuario_pesquisado->getImg(); ?>";

I noticed that the value is received by php, however it is not passed to the src of the image

    
asked by anonymous 13.10.2018 / 17:37

3 answers

0

In the head of the page where the javascript will be

<script src="local/do//jQuery.js"></script>

In the HTML context / Who shows the image

<img id="imagemPerfil"
     alt="profile image"
     class="circle z-depth-2 responsive-img activator gradient-45deg-light-blue-cyan gradient-shadow">

In the context of Javascript / Who requests the image

<script>
    $(document).ready(function () {
        var params = {
            Request: "GetImgPerf"
        };
        $.get("PerfilUsuarioController.php", params, function (respImg) {
            $("#imagemPerfil").attr("src", respImg);
        });
    });
</script>

In the part where you enter the ProfileUserController.php, it is where I did the test here at home, but to work for you, check in your project, what is the path to access the image.

Generic example PHP / Who provides the image

class PerfilUsuarioController {

    public function verificarRequest() {
        $request = $_GET["Request"];
        switch ($request) {
            case "GetImgPerf":
                $this->getImgPerfil();
                break;

            default:
                break;
        }
    }

    public function getImgPerfil() {
        // Codigo de busca do usua ou qualquer outra verificação
        print $usuario_pesquisado->getImg();
    }

}

$perf = new PerfilUsuarioController();
$perf->verificarRequest();
    
13.10.2018 / 19:46
0

Hello,

I see two options that you can use, maybe with more details of how you want to use I have other ideas, but let's:

You can assign the direct img in src:

<img id="imagemPerfil" src="<?php echo'../img/perfilUsuario/'.$usuario_pesquisado->getImg(); ?>" alt="profile image"  class="circle z-depth-2 responsive-img activator gradient-45deg-light-blue-cyan gradient-shadow">

Or you create an Ajax request via javascript and in OnSucess you change the image.

    
13.10.2018 / 17:50
0

This may be browser or server caching especially if you are using a CDN.

Try placing a url with parameters to see if it does not resolve. Example: /image/archive.jpg

    
13.10.2018 / 18:07