PASSWORD RESET

Your destination for complete Tech news

PHP

How to pass variables from PHP to javascript?

413 0
< 1 min read

To pass variables from PHP to JavaScript, you can use the echo statement to output the JavaScript code with the variables included.

Here’s an example of how you can do it:

<?php
$name = 'John';
$age = 30;
?>

<script>
var name = '<?php echo $name; ?>';
var age = <?php echo $age; ?>;
</script>

In this example, the PHP variables $name and $age are passed to the JavaScript code as string and integer values, respectively.

Note that you need to use single quotes around the PHP code when it is inside a double-quoted JavaScript string, and vice versa. This is to avoid conflicts with the string delimiters.

Another option is to use JSON encoding to pass more complex data structures (e.g., arrays or objects) from PHP to JavaScript. You can use the json_encode function to convert a PHP value to a JSON-formatted string, which can then be parsed in JavaScript using the JSON.parse function.

<?php
$data = ['name' => 'John', 'age' => 30];
$json = json_encode($data);
?>

<script>
var data = JSON.parse('<?php echo $json; ?>');
</script>

In this example, the PHP array is converted to a JSON string and passed to the JavaScript code, which parses it back into an object.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.