简体   繁体   中英

php variable to javascript with json_encode

I know this topic was already discussed a few times but I can't seem to find what I'm doing wrong.

What I'm trying to do: The user types in a number and by clicking on the button creates a table with that number of columns.

Heres the php:

<?php
$twig = require_once('bootstrap.php');
$hostname = 'localhost';
$username = 'root';
$password =  '';
$conn = new PDO("mysql:host=$hostname;dbname=mydb", $username, $password);

echo $twig->render('index.html', array());

$numOfRows = 1;

if(isset($_POST['button'])){
    $numOfRows = $_POST['num_input'];
}

html/javascript:

<html>
<head>
<script>
function insertRows(){
    var numOfRows = <?php echo json_encode($numOfRows) ?>;
    var out = "<table><tr><th>test</th>";

    for (i = 0; i < numOfRows; i++){
        out += "<th>test</th>";
    }

    out += "</tr></table>";
    document.getElementById("table").innerHTML = out;
}
</script>
</head>

<body>
<form action="index.php" method="post">
  <textarea id="num_input" name ="num_input"></textarea>
  <button type="button"  name="button" onclick="insertRows()"> Go </button>
</form>

<p id="table"></p>

</body>
</html>

Theres no error or anything since I'm not using a IDE, just doing it in vim but the error is that is just doesn't happen. If i change "numOfRows" in the for loop to a number it works, so I'm pretty sure the json_encode is the problem.

Thanks!

EDIT: Just to test it, I used a string variable $str = "test"; the php file, and instead of using the for loop, I just edited javascript to

var str = <?php echo json_encode($str); ?>;
alert(str);

and I also tried

var str = <?php echo $str; ?>;
alert(str);

but nothing works.

json_encode is not necessary in this case.

Simply replace

var numOfRows = <?php echo json_encode($numOfRows); ?>;

with

var numOfRows = <?php echo (int)$numOfRows; ?>;

Edit: You are missing a ; on the

<?php echo json_encode($numOfRows) ?>

Should be

<?php echo json_encode($numOfRows);?>

And in these cases, if would be good to check the server log, this will automaticly make you better at finding these mistakes yourself.


You are mixing up ints and strings. The database will in PHP always return strings and the way you are using the variable as an int in a for loop.

The following change i believe would achieve the right result.

$numOfRows = intval($_POST['num_input']);

Where you use PHP's conversion to integer function there is at a global level.

You did not forget any $. JS does not need $ for variables.

As far as your json_encode is concerned, if you are just passing an integer from PHP to JS, there is no need to json_encode. Just pass the variable to JS as <?=$numOfRows?> in the JS source.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM