Pass Values from PHP to Javascript
There are many ways to pass PHP variables to Javascript but I will only cover 3 most common:
1. Echo the data.
2. Use a hidden field or element.
3. Use a data attribute
But the above code can cause an issue depending on the data type and it's value, so we use
In PHP:
In Javascript:
In Javascript:
To check the values, we can simply log it on the console:
It is also possible to use JSON coming from an AJAX response to pass the value from PHP to Javascript but that would require additional server request so I do not recommend that unless you're actually receiving your data through an AJAX request.
1. Echo the data.
2. Use a hidden field or element.
3. Use a data attribute
1. Echo the data.
The first one which is the simplest can be done as follows:var data = <?php echo $data; ?>;
But the above code can cause an issue depending on the data type and it's value, so we use
json_encode
to convert the data.In PHP:
$name = "John O'Reily"; // a string with single quote
$age = 14; // an integer number
$address = array( // an array
'street' => '123 Street',
'city' => 'XYZ City'
);
In Javascript:
var name = <?php echo json_encode($name); ?>;
var age = parseInt(<?php echo json_encode($age); ?>);
var address = <?php echo json_encode($address); ?>;
2. Use a hidden field or element.
<span id='name'><?php echo $name ?></div> // with display:none css property
<input type='hidden' id='address' value='<?php echo json_encode($address)?>'>
In Javascript:
var name = $('#name').text();
var address = $('#address').val();
3. Use a data attribute
<div id="person"
data-name=<?php echo json_encode($name) ?>
data-address='<?php echo json_encode($address) ?>'>some text</div>
var name = $('#person').data('name');
var address = $('#person').data('address');
To check the values, we can simply log it on the console:
console.log('Name: ' + name);
console.log('City: ' + address.city);
It is also possible to use JSON coming from an AJAX response to pass the value from PHP to Javascript but that would require additional server request so I do not recommend that unless you're actually receiving your data through an AJAX request.
Comments
Post a Comment