1

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>
5
  • 2
    You can't echo inside an echo. Commented Mar 27, 2020 at 21:41
  • And I wouldn't opt to echo the button anyway. Separating php and html in mixed code makes it more readable (reduces the number of quotes as well as quoting issues that come along with it). Commented Mar 27, 2020 at 21:44
  • PHP runs on the server, before the page is sent to the browser. PHP code can't run in the browser. Commented Mar 27, 2020 at 21:44
  • @codemaster96 check out my answer please Commented Mar 27, 2020 at 22:11
  • Could you edit the question so that it is clear what you are asking? What js array? What ajax? There is nothing like that in your example. Commented Mar 27, 2020 at 22:21

3 Answers 3

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Yes you are right!:) Thank you for the help, it works fine
0

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>

1 Comment

Yes its okay, but this method don't work when im printing the products on the web site, because i need the information about the product where i click, but anyway thank you for help :))!
0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.