简体   繁体   中英

Passing PHP variable to Javascript Array

i want to pass PHP variable to Javascript array. It is a test code, but in further i want to pass the printed product id's and name's to this ajax function to send it to cart The code above is working without printing the button with echo.Any better ideas are welcome :)

 <html>

<?php 

$num=3;

echo "<button onclick='funkt('<?php echo $num ?>');'>cc</button>
";

?>
</html>
<script>

function funkt(x){
 var c=x;
alert(c);
}



</script>

You weren't properly escaping the quotes inside the echo statement. Also, HTML attributes use double quotes (onclick="..."), not single quotes. Try this:

<!DOCTYPE html>
<html>
<head>    
<script>
    function funkt(x) {
        var c = x;
        alert(c);
    }
</script>
</head>
<body>
<?php
$num = 3;
echo "<button onclick=\"funkt('" . $num . "');\">cc</button>";
?>
</body>
</html>

Better option is to add an input field of type hidden and pass the number/name/ID to it. On submission of form or button click, you can fetch it wtih the field Id and pass the value to ajax.

<input type="hidden" id="number" value="<?php echo $num;?>" />


<script>
    function funkt(x) {
        var c = document.querySelector("#number").value;
        alert(c);
    }
</script>

You can try to declare variable inside "script" tag, and then use this variable in the javascript afterwards like this:

<?php  $num = 5;  ?>   
    <script>
          var link_label = '<?php echo $num ?>';

          //use your link_label value to load it in ajax here or in other files that has been loaded after this script

    </script>

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