0

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

  }
}

3 Answers 3

1

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...
        }
     });
}
Sign up to request clarification or add additional context in comments.

1 Comment

He didn't say anything about AJAX and based on his code provided, he doesn't need it.
0

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;

2 Comments

This is the right answer. Javascript has no variable called $abc. PHP echos var test = ... so test is the variable to compare in the condition.
@John php serves up the page so there is no need to make an ajax call back to the server from the client on page load.
0

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.

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.