Problems in passing PHP array to JavaScript - javascript

I understand that the format for passing a PHP array to Javascript is:
<script type="text/javascript">
var obj = <?php echo json_encode($php_variable); ?>;
</script>
I have a php function that stores some values in a longitude and latitude array. These array do hold the right values within php since print_r() within php shows me that the array is correct.
print_r($latitude_array);
print_r($longitude_array);
Now, I pass on this array to JS in this manner:
<script>
var lati_array = "<?php echo json_encode($latitude_array); ?>";
var longi_array = "<?php echo json_encode($longitude_array); ?>";
alert(lati_array[0]);
</script>
In the beginning, when I open the HTML file, it shows me an empty array (which is expected because the PHP arrays aren't filled yet). Then user enters something, the php arrays are filled up with longitudes and latitudes. These values should now be passed to JS. However, it doesn't alert anything after that. I can't be sure if array is successfully passed to JS. What am I missing?

Try this:
<script>
var data = <?php echo json_encode( $data ); ?>;
</script>

Try like below:
<?php
$array_var = array(111, 222, 333, 444);
?>
<script>
var array_var = "<?php echo json_encode($array_var); ?>";
console.log(array_var);
array_var = JSON.parse(array_var);
console.log(array_var);
alert(array_var[0]);
</script>

You are getting a string in lati_array , Try to convert it into json like this:
<script>
var lati_array = "<?php echo !empty($latitude_array) ? json_encode($latitude_array) : ''; ?>";
var longi_array = "<?php echo !empty($longitude_array) ? json_encode($longitude_array) : ''; ?>";
lati_array = JSON.parse(lati_array);
alert(lati_array[0]);
</script>

Related

How to pass php array value to javascript variable

I have working on core php, i have getting all values from database(select query) in this i have to executed while loop and changed to array variable after i have to pass that array value to javascript variable how to pass this please help.
here my code:
<?php
include "db_connection.php";
$locations=array();
$query = $conn->query('SELECT `pg_address` FROM `tbl_master_property` limit 10');
while ($row =$query->fetch_assoc()) {
$list[] = $row;
}
$locations=$list;
//echo "<pre>";print_r($locations);die;
//echo "<pre>";print_r($cart_info_json);die;
?>
<script type="text/javascript">
var geocoder;
var map;
var data = <?php echo json_encode($locations); ?>;
//console.log(data);
alert(data);
in this alert is showing (object,object,object,object,object,object,object,object)
try :
alert(JSON.stringify(data));
but i would recommend console.log(data); and debug in the console.

Passing my PHP variable value to Js file

Hiii Everyone,
<script src="../../record/recordmp3.js?id=<?php echo $_GET['id'];?>&&test_no=<?php echo $_GET['test_no'];?>"></script>
<script type="text/javascript" data-my_var_1="some_val_1" data-my_var_2="some_val_2" src="/js/somefile.js"></script>
And I tried to get that passing value in recordmp3.js is
var student_id = this_js_script.attr('data-my_var_1');
var test_no = this_js_script.attr('data-my_var_2');
And also by
var student_id = "<?php echo $_GET['id'];?>";
var test_no = "<?php echo $_GET['test_no'];?>";
And my value is not passing correctly.Instead only '0' is passing In my index page I have some PHP variable value I need to pass that value to recordmp3.js file.Please help me to solve this issue.Thank you so much in advance.
I tried like below its working fine
<script src="../../record/recordmp3.js"></script>
<script type="text/javascript">
MYLIBRARY.init(["<?php echo $id; ?>", "<?php echo $test_no; ?>"]);
MYLIBRARY.helloWorld();
</script>
var MYLIBRARY = MYLIBRARY || (function(){
var _args = {}; // private
return {
init : function(Args) {
_args = Args;
// some other initialising
},
helloWorld : function() {
window.id= _args[0];
window.test_no= _args[1];
}
};
}());
You need to convert these values to json array. You cannot directly assign the php values to JavaScript variables.
Hope this answer is useful. Please let me know if you find any difficulties on converting to json value.
.js files don't execute and compile the php files,so in order to access the php variables in javascript the file should be .php.
script.php
<?php
$foo = 'Hello cool';
?>
<script>
var foo ='<?php echo $foo ?>';
console.log(foo);
</script>
i hope this example will solve your issue

Passing Array From PHP to JQuery json_encode

I have an HTML form generated by php which has a dropdown of voucherproviders.
I want to select the provider and have this populate the form for editing.
Here is my JQuery code:
$(document).ready(function() {
$(document).on('change','#id_voucherprovider',function(){
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
//The value I have got from the drop down is....
var value = $('#id_voucherprovider option:selected').val();
var vendortext = $('#id_voucherprovider option:selected').text();
//so the voucher provider is
alert(vendortext);
$('.ftext input').val(vendortext);
$("textarea#id_vendornotes").val(voucher_providers[value]);
});
});
voucherproviders is not being passed into the JQuery despite the echo json_encode($voucher_providers); code working when inline with the php code.
It seems to return a null array. Can anyone see what is wrong?
Many Thanks
Dave
var voucher_providers = <?php echo json_encode($voucher_providers); ?>;
json_encode returns a string, unless it is parsed it will not be usable. Use JQuery .parseJSON and you should have better results. :)
var jsonString = <?php echo json_encode($voucher_providers); ?>;
var voucher_providers = $.parseJSON(jsonString);
try this (note the quotes):
var voucher_providers = JSON.parse('<?php echo json_encode($voucher_providers); ?>');
parse your json ex: obj = JSON.parse(data);
Hi please check the json format at below site:-
http://jsonlint.com/
and check if this is fine.

Unable to print PHP variable using JS

I understand that this question has been asked a lot of of times, but the solutions posted there don't seem to work for me. I have a code as follows:
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>
I actually want to pass a PHP variable to a JS function, but I wanted to try if printing the variable works first. Please help me out.
instead of
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>
<?php
$phpVar="jajha";
?>
try
<?php
$phpVar="jajha";
?>
<script>
var JSvar = "<?php echo $phpVar ?>";
document.write(JSvar);
</script>

convert JS var to PHP and vice versa

Here I am getting values from textarea in array variable.
After that I convert javascript variable to PHP variable and perform some processing over it.
After process completed again I convert PHP to JS and alert. But when I alert, it gives empty result.
<script>
$( "#convert" ).click(function() {
var arabic = document.getElementById("ar").value; // ar is id of text area
<?php $ar_terms = "<script>document.write(arabic)</script>"?>
<?php
$string=implode(",",$ar_terms);
$result = array();
foreach ($ar_terms as $term) {
// echo $Arabic->ar2en($term);
array_push($result, $Arabic->ar2en($term));
}
$result=implode(",",$result);
?>
var arabic = new Array();
arabic='<?php echo $result; ?>';
alert(arabic);
});
</script>
Entire code is here : https://gist.github.com/karimkhanp/d4ac41fa864fd8ae0521
You can do one thing in this scenario to pass the variable from PHP to js. You can convert the array using json_encode() before echoing:
$result=json_encode( implode(",",$result) );
As a result, when you assign this variable to js in the <?= ?> block, it will read the json string and thus the array will be assigned:
arabic='<?php echo $result; ?>';

Categories