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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Keroro Chan
  • 99
  • 1
  • 10

3 Answers3

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.

Daniel Cheung
  • 4,779
  • 1
  • 30
  • 63
  • why does the code work when I put after $v1 in php? It seems that the encapsulation will happen for this code. – Keroro Chan Feb 11 '16 at 09:08
  • 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. – Keroro Chan Feb 11 '16 at 09:11
  • @KeroroChan Sorry, I don't really understand your reply :/ Do you speak Chinese? You just need to do this: `` before you use the variable on your webpage.. – Daniel Cheung Feb 11 '16 at 09:16
  • I have updated my second way which works for me but I don't want to put at the bottom. But, why there are no encapsulation problems? – Keroro Chan Feb 11 '16 at 09:26
  • @KeroroChan You don't have to put that at the bottom. The ` – Daniel Cheung Feb 11 '16 at 09:29
  • @KeroroChan Regarding the "encapsulation problem". You see, the browser only scans the code inside the ` – Daniel Cheung Feb 11 '16 at 09:31
  • You mean that is in which is the same scope as $name? – Keroro Chan Feb 11 '16 at 09:35
  • @KeroroChan no, you have to understand, that you don't regard PHP and JS together. PHP only prints out the text for JS to process, they don't know each other. I'm talking about **scope** in JavaScript :) – Daniel Cheung Feb 11 '16 at 09:41
  • I don't want to separate the php code and put it at the top. The same reason why I want to put the javasript variable at the top is I don't want the javascript variables separated. However, you put the php code at the top and the php code is separated instead of javascript code. – Keroro Chan Feb 11 '16 at 09:42
  • @KeroroChan You don't need to. Do you prefer me explaining in Chinese? If you think it is more readable? – Daniel Cheung Feb 11 '16 at 09:44
  • You mean that v1 in $(document).ready(function(){ var v1 = ; }); can only be used in $(document).ready(function(){ } and cannot be used in other javascript functions because of different scope? – Keroro Chan Feb 11 '16 at 09:47
  • @KeroroChan no, the basic problem revolving your question be "JS scope understanding". You cannot access a higher scope from a lower/local scope. The one that changes scope in JS is mainly (I say this because I am not too certain if there is another way to change scope) `function(){}` – Daniel Cheung Feb 11 '16 at 09:49
  • If I have to put php code at the top, I prefer to put the script at the end. Thank you for explaining the scope problem. – Keroro Chan Feb 11 '16 at 09:50
  • @KeroroChan If you are still not sure, you're welcome to ask more! :) – Daniel Cheung Feb 11 '16 at 09:50
  • @KeroroChan Also, I need to stress that there is no restraints on where to put PHP and JS code. FYI, here is my answer to "Where to put JS libraries on a webpage". The same goes to "code" http://stackoverflow.com/questions/34702909/where-to-insert-javascript-libraries-and-css-in-my-html-code/34703110#34703110 – Daniel Cheung Feb 11 '16 at 09:52
  • Thank you, Daniel Cheung – Keroro Chan Feb 11 '16 at 15:33
  • Daniel Cheung, do you have facebook,etc? If I have problems, I want to ask you first. – Keroro Chan Feb 11 '16 at 15:36
  • @KeroroChan I don't want to disclose my Facebook, besides, I'm not that good either. If you ask on StackOverflow, you might get an answer faster :) People here are friendly (if you don't frustrate them with hard to understand questions and show that you have researched but to no avail) – Daniel Cheung Feb 11 '16 at 15:39
  • OK! Thank you very much. – Keroro Chan Feb 11 '16 at 15:45
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);
});
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">
Niklesh Raut
  • 34,013
  • 16
  • 75
  • 109