0

I've already seen some similar posts but I think my case is different. I have the following code:

$(".imagem .bottom-buttons").on("click", ".ver-emb", function(event){
        var Image = <?php echo $row->embalagem; ?>;
//row-embalagem comes from a query search to the database.
        $(".slider-img").css("background-image", "url(../assets/imagens/<?php echo $row->embalagem; ?>)");
        $(this).addClass( "ver-prod" );
        $(this).removeClass( "ver-emb" );
        $(this).text( "Ver Produto" );
    });

I've read that you need to put the php variable into jquery variable, but how do I apply that new Jquery variable to the background-image url ?

1
  • you missed quotes, var Image = '<?php echo $row->embalagem; ?>'; this may work Commented Jun 8, 2018 at 12:25

3 Answers 3

1

You'd use it the same way you use any variable in JavaScript:

"url(../assets/imagens/" + Image + ")"

Additionally, if your variable is a string (you're using it as a string) then strings need to be surrounded by quotes:

var Image = "<?php echo $row->embalagem; ?>";
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. I totally forgot that I could append that way.
1

Try this :

$(".imagem .bottom-buttons").on("click", ".ver-emb", function(event){
            var Image = '<?php echo $row->embalagem; ?>';
    //row-embalagem comes from a query search to the database.
            $(".slider-img").css("background-image", "url(../assets/imagens/"+image+")");
            $(this).addClass( "ver-prod" );
            $(this).removeClass( "ver-emb" );
            $(this).text( "Ver Produto" );
        });

Comments

1

Just append the Image var in the url, like this:

$(".imagem .bottom-buttons").on("click", ".ver-emb", function(event){
    var Image = "<?php echo $row->embalagem; ?>";
    $(".slider-img").css("background-image", "url(../assets/imagens/"+Image+")");
    $(this).addClass( "ver-prod" )
    $(this).removeClass( "ver-emb" );
    $(this).text( "Ver Produto" );
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.