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?