converting with json_encode() - javascript

<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = '<?php echo json_encode($array); ?>';
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I have PHP array with two elements, when I converting this array to javascript array with json_encode()javascript divide my PHP array into set of chars, so in javascript array in a result i have a lot of elements. How to convert PHP array with two elements to javascript array with the same two elements?

You php function json_encode will give you a valid object, that's in fact what it means, JavaScript Object Notation.
So by using it as it is you will create an object in your JavaScript code. By enclosing it between apostrophes you are making it a string (who's value can be parsed as JSON).
So the simplest change would be to remove the apostrophes. So this line:
var js_array = '<?php echo json_encode($array); ?>';
Should become
var js_array = <?php echo json_encode($array); ?>;

The problem is that you have enclosed the json_encode in colons so you are converting it to a string. The javascript it produces is like this:
var js_array = '["first elem","second elem"]';
Here js_array is an string but you want an array. What you have to do is to produce the json directly as it will yield an array:
var js_array = <?php echo json_encode($array); ?>;

Replace you code with the following code..
<?php
$array = array("first elem", "second elem");
?>
<html>
<head>
</head>
<body>
<script>
var js_array = <?php echo json_encode($array); ?>;
for (var i = 0; i < js_array.length; i++)
{
document.write(js_array[i]);
document.write("<br>");
}
</script>
</body>
I hope its help you.....

Related

PHP / JS - Send values from php to a js array

I have a php array "$values", i want to transfer its values to a js array, which is working well, the only problem i'm getting is that it's making the 2 values sended stuck together as "onetwo" while i want them to be as two different values ["one","two"] in my Js array.
<?php
$values= ["one", "two"];
?>
<script>
var Js_array = [];
Js_array.push('<?php
for ($x = 0; $x < count($values); $x++) {
echo $values[$x];
}
?>');
alert(Js_array);
</script>
Thanks for your help.
You are currently echoing all the items of the php array into ONE instance of the Js_array.push() function, so Js_array.push adds all the items of your php array as 1 item into the javascript array.
You instead should invoke Js_array.push() on each item of the php array, so each item can be added to the javascript array seperately. The below code demonstrates the required modification:
<?php
$values = ["one", "two"];
?>
<script>
var Js_array = [];
<?php
for ($x = 0; $x < count($values); $x++) {
echo 'Js_array.push("'.$values[$x].'");'; // call Js_array.push on each item of php array;
}
?>;
alert(Js_array);
</script>
<?php
$values= ["one", "two"];
function addQuotes($each_value){
return "'".$each_value."'";
}
?>
<script>
var Js_array = [<?php echo implode(",",array_map("addQuotes",$values)); ?>];
alert(Js_array);
</script>

how to pass php array value to javascript without using JSON

I have a simple calculation from php database, which needs to be used in javascript, how to do it?
<script>
function check(){
var ramt=document.getElementByName('refundedamount[]');
var bal1=[];
<?php for each($balance1 as $val){
echo 'bal1.push('.$val.');';
} ?>
. . .
} </script>
<form onsubmit="return check()";
<?php
$balance1=array();
while($row=mysqli_fetch_assoc($result)){
$income=$row['totalincome'];
$exp=$row['totalexp'];
$balance=$income-$exp;
$balance1[]=$balance;
...... ?>
<input type="text" name="refundedamount[]"/>
</form>
How to use and read values of $balance1[] array into JAVASCRIPT. without using JSON. basically I want to cross check the value of php $balance1 array and input text array " refundedamount[]".
Without JSON, you can loop each value.
<?php
$balance1 = array( 1,2,3,4,5 );
?>
<script>
var balance1 = [];
<?php
foreach( $balance1 as $val ) {
echo 'balance1.push( ' . $val . ' );';
}
?>
console.log( balance1 );
</script>
Will result to
Array [ 1, 2, 3, 4, 5 ]
PHP side:
$arrayJSON = json_encode($balance1) to convert to JSON format.
JS side:
var array = JSON.parse("<?php echo $arrayJSON;?>");
Hope this help!
You can convert the php array into a javascript object then convert that object into an array, eg if it has numeric indices:
<script>
var obj = <?php echo json_encode($phpArray) ?>;
var arr = Object.keys(obj).map(function(k) { return obj[k] });
// Or if you're using ES6
var arr = Object.values(obj);
</script>

Problems in passing PHP array to 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>

SyntaxError: unterminated string literal var address = "

I've this problem at the var address line, i think to have write all correctly or not?
<?php for ($i = 1; $i <= count($data); $i++) { ?>
var address = "<?php echo $address[$i].','.$city[$i].','.$region[$i] ?>";
alert(address);
<?php } ?>
You're generating javascript with php and the error you get comes from the javascript part, not php. I guess that one of your variables like $address contains something that isn't valid in js strings, like a newline. The best practice is to use json_encode to encode values for use in javascript:
var address = <?php echo json_encode($address[$i].','.$city[$i].','.$region[$i]) ?>;

Pass JS value in php

How can I send JavaScript variable value in php?
Like :
for(var j=0;j<count_array_item;j++){
get_item = <?php echo json_encode($cld[???]['title']); ?>; //want to get 'j' value.
}
Try this code. foreach loop store the value in js get_item array.
<script type="text/javascript" language="javascript">
var get_item = new Array();
<?php foreach($cld as $val){ ?>
get_item.push('<?php echo json_encode($val["title"]); ?>');
<?php } ?>
</script>

Categories