1

I have javascript function using javascript variable from php variable using jQuery. The code is shown below:

jQuery:

$(document).ready(function(){
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
});

javascript function

function abc(){
alert(v1);
}

I cannot print out the value of v1, but when I do not use jquery to send php variable to javascript variable, I use the below code after $v1 in php

<script type="text/javascript">
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
</script>

And the function can print out value of v1.

But, I want to see which variables I have already used and see them at the top instead of at the bottom. So, I decide to use jquery but it fails. Where does it go wrong?


the second way which works for me is shown below:

<!DOCTYPE html>
<html>
<head>
    <script>
      function abc(){
      alert(v1);
      }
    </script>
</head>
<body>
<?php
$sql = "SELECT r_ID,r_cname,address FROM rest ORDER BY count2+count3 DESC";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_array()){
    array_push($name,$row["r_cname"]);
}
}
?>
    <script>
      var v1 = <?php echo json_encode($name); ?>;
    </script>

</body>
</html>

Why there are no encapsulation problems?

7
  • Change the extension of the file to .php Commented Feb 11, 2016 at 8:46
  • 1
    Your alert(v1) needs to be inside the same function the var v1 = ... is in. And the JSON needs to be valid to print out the valid object. Commented Feb 11, 2016 at 8:47
  • specify where is your all code is exist ? in which files ? Commented Feb 11, 2016 at 8:53
  • Little Phild, the file has already been set as .php Commented Feb 11, 2016 at 8:54
  • LearningMode, the code is put in the same file let's say abc.php Commented Feb 11, 2016 at 8:56

3 Answers 3

3

Your alert(v1) needs to be inside the same function the var v1 = ... is in. And the JSON needs to be valid to print out a valid object.

A PHP printed variable often need not to be in jQuery. It almost certainly not need to be inside a jQuery function, trust me, because it is often just a piece of data.

I always use this method/practice:

<?php
//My businesses
?>
<!DOCTYPE html>
<html>
    ...
    <head>
        <script>
            //By the way, HTML5 don't require you to state the type of script, it is defaulted to JavaScript.
            var x = <?php echo json_encode($x, JSON_UNESCAPED_UNICODE);?>
        </script>
        <script>
            //Rest of my code
            $(function(){
                //My jQuery here
            })
        </script>
    </head>
    <body>
    ...
    </body>
</html>

Why declaring the variable inside jQuery "doesn't" work

It does, but outside the scope of $(function(){}), no one can access variables defined inside. It is a basic mechanism of JS. On the other hand, the function(){} inside $() is an argument, that is the second reason it doesn't work getting the value outside.

Example:

var a = 3;

function(){
    var b = 4;
    a; //<-- 3
};

b; //<-- undefined

Why the second script worked

Let's assume your code looks like this:

...
<script>
    var v1 = <?php echo json_encode($v1, JSON_UNESCAPED_UNICODE);?>
</script>
...
<script>
    $(function(){
        v1; //There is a value
    })
</script>
...

Because your new v1 variable is defined just under <script>, it is a global variable. A global variable can be accessed anywhere on the webpage.

In contrast, a local variable cannot be accessed outside the scope it is in. Look at this tree diagram:

window
|- v1
`- function x
   |- v2
   `- function y
      `- v3

Basically, a variable can only be accessed by its children and never its parents. So:

v1 can be accessed inside inside and outside of function x and function y but v2 can only be accessed inside of function x and function y and v3 can only be accessed inside function y

Here is a table of what variables can be accessed where:

   globally | function x | function y
------------|------------|-----------
v1     ✓    |      ✓     |     ✓
------------|------------------------
v2          |      ✓     |     ✓
------------|------------------------
v3          |            |     ✓

Final answer

You just need to do this: <script>var v1 = <?php echo json_encode($v1);?></script> before you use the variable on your webpage.

Sign up to request clarification or add additional context in comments.

19 Comments

why does the code work when I put <script type="text/javascript"> var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>; </script> after $v1 in php? It seems that the encapsulation will happen for this code.
I just simply my question. Actually, I need to do many stuffs to get $x in php. So, it is hard to implement using your method.
@KeroroChan Sorry, I don't really understand your reply :/ Do you speak Chinese? You just need to do this: <script> var v1 = <?php echo json_encode($v1);?> </script> before you use the variable on your webpage..
I have updated my second way which works for me but I don't want to put <script> var v1 = <?php echo json_encode($v1);?> </script> at the bottom. But, why there are no encapsulation problems?
@KeroroChan You don't have to put that at the bottom. The <script> tag can be places in the <head> or <body>. Yo don't even need to put the JS + PHP code in an isolated tag. Just place the line of code somewhere globally.
|
1

Your issue lays in timing and/or scope.

This code will run after the page is done loading and all the variables declared in it are encapsulated and exist only within it:

$(document).ready(function(){...})

Try this:

// Declaring variable in global scope.
var v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;

$(document).ready(function(){

    // Open console to view result
    console.log(v1);
});

Comments

0

Its working, follow the sequence

<?php
    $v1 = ["a","b","c"];
?>
<script type="text/javascript">
v1 = <?php echo json_encode($v1,JSON_NUMERIC_CHECK); ?>;
abc();
function abc(){
    alert(v1);
}
</script>

------------------- Updated code if js is before php code ----------------------

<script type="text/javascript">
$( document ).ready(function() {
    v1 = $("#v1").val();
    abc();
    function abc(){
        alert(v1);
    }
});
</script>
<?php
    $v1 = ["a"=>"aa","b"=>"bb","c"=>"cc"];
    $v1_json = json_encode($v1,JSON_NUMERIC_CHECK);
?>
<input type="hidden" value='<?php echo $v1_json; ?>' id="v1">

3 Comments

I don't want the script after php.
@KeroroChan have updated my code hope you want something like this ?
It may work but it has too much overhead like <input type="hidden" value='<?php echo $v1_json; ?>' id="v1">. But, thanks for your answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.