Showing posts with label js array. Show all posts
Showing posts with label js array. Show all posts

Friday, April 10, 2015

Assign value or array in PHP variable to Javascript variable.

<?php
$name = 'Einstein';
$categories = array('1'=>'Red', '2'=>'Green', '3'=>'Blue');
?>

<script type="text/javascript">
// Assign a PHP value/string to JS variable.
var name = '<?php echo $name; ?>';
console.log(name);                       // Einstein

// Assign a PHP array to JS variable.
var categories = JSON.parse('<?php echo json_encode($categories); ?>');
console.log(categories[3]);           // Blue
</script>

Learn JavaScript - String and its methods - 16

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>String and it's methods - JS...