Dumb_Shock
Dumb_Shock

Reputation: 1008

How to access variable declared in PHP by jquery

For example i declare some variable like test in server side of my PHP

echo('var test = ' . json_encode($abc));

Now i want to use this test variable in Jquery ..how can i use it?

What function do i need to use it?

For Example i have:

I have back end PHP code something like this

$abc = no
echo "var test= ".json_encode($abc);

I want jquery to do the following action(client side)

$(document).ready(function(){
function(json) { 
if($abc == no )//this i what i want to be achieved

  }
}

Upvotes: 0

Views: 432

Answers (3)

Aaron
Aaron

Reputation: 10848

If you really wanted to (though I don't think this is a very good practice), you could echo the PHP variable's value into a javascript variable like this:

<script type="text/javascript">
   var phpValue = <?php echo $abc; ?>;
   alert(phpValue);
</script>

I can see this being dangerous in many cases, but what this effectively does is echo the value of $abc onto the page (inside of your script tags of course). Then, when the javascript it run by the browser, the browser sees it like this:

<script type="text/javascript">
    var phpValue = no;
    alert(phpValue);
</script>

This is very basic, but you get an idea of what you could do by using that kind of code.

Upvotes: 0

KSDaemon
KSDaemon

Reputation: 366

I think, you dont understand the diference between frontend (JavaScript) and backend (PHP). You can not directly access php variables from javascript. You need to make Ajax-request to some php file, that will return some data that you need in format that you specify. for example:

<?php
    $result = array('abc' => 'no');
    echo json_encode($result); 
?>

This is serverside script called data.php. In Javascript you can make so:

$(document).ready(function(){
    $.getJSON('data.php', function (data) {
        if(data.abc === 'no') {
            your code...
        }
     });
}

Upvotes: 1

SeanCannon
SeanCannon

Reputation: 77956

You're comparing the wrong variable:

<?php

echo <<<JS
    <script type="text/javascript">
        var test = {json_encode($abc)};
        $(document).ready(function(){
            if(test == 'no' )
                // here you go
            }
        });
    </script>
JS;

Upvotes: 0

Related Questions