PHP echo variable does not work in jQuery

0

I was reading by stackoverflow in English the way to receive in jQuery the value of a PHP variable and I found this way:

$(document).ready(function(){
    $(".topic").click(function () {
        var postId = "<?php echo $post[\'id\']; ?>";
        alert(postId);
    });                         
});

And at the moment of executing the script, in the alert I see the PHP code literal instead of executing the echo and showing the value. How can i fix this? Thanks.

    
asked by Frey Stroud 21.03.2017 в 06:36
source

3 answers

0

Your code must be embedded in your html, usually in a file with php extension and be interpeded by php.

Something like this:

<?php 
$post['id'] = 10; 
?>
<html>
 <head>
     <script>


        $(document).ready(function(){
        $(".topic").click(function () {
            var postId = "<?php echo $post['id']; ?>";
            alert(postId);
            });                         
        });

     </script>
 </head>
 <body>

 </body>
</html>

Here's an example

Anyway I would recommend you to handle a single javascript object where you save all the variables that you upload from the server the first time.

<script>
 var datosDeInicio = <?php echo json_encode($miVariable); ?>;
</script>
    
answered by 21.03.2017 / 06:56
source
3

I think you could avoid using backslash "\" because those would work if you were using double quotes inside other double quotes "\" ", in this case as you use single quotes inside double quotes" '"is not necessary.

$(document).ready(function(){
    $(".topic").click(function () {
        var postId = "<?php echo $post['id']; ?>";
        alert(postId);
    });                         
});

and just to be sure, your file is .php and there is the variable $ post ['id']? It would be very helpful if you shared more part of your code and more information about the problem.

    
answered by 21.03.2017 в 06:55
0

@MalCam is right, if you want to use php variables in JavaScript, you will have to process the file in PHP ... that is, the JS must be found inside a .php file

    
answered by 22.03.2017 в 17:02