Store value of php array variable to javascript array variable - php

i have some problem, how to store value of php array variable to javascript array variable because i want to manipulate data in javascript
here's my code
<?php
$coor= array('-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914');
?>
And i want to store all the values from $coor to var allcoor = new Array(), what i've been trying is use json_encode
<script>
var allcoor=new Array();
allcoor = "<?php foreach ($cobadeh as $t){echo json_encode($t);} ?>";
//for some example of manipulation array variable javascript
mySplitResult = allcoor[0].split("|");
...
</script>
What I want is manipulation of javascript array variable, and that code didn't work, can anyone help?

You need to start out with a php array that mirrors the javascript array that you want. Then output the results of json_encode on that array.
For this I am assuming you want an array of arrays.
<?php
$coorStr = "-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914";
$coor= explode("|",$coorStr);
$coor = array_map(function($a) { return explode(",", $a); }, $coor);
?>
allcoor = <?php echo json_encode($cobadeh); ?>;
The first explode command splits the string into an array of elements containing each of the coordinate pairs.
The array_map call splits each of element in an array.
Finally the json_encode formats the data correctly for a javascript assignment.
Since the variable is a php array and you want it as a javascript array

first you create an array in the php side
$coor='-7.175993,112.650729|-7.17616,112.651139|-7.176591,112.650968|-7.176413,112.650552|-7.176104,112.650437','-7.176331,112.649924|-7.17632,112.650053|-7.176629,112.650048|-7.176629,112.649914';
$corar = explode("|", $coor);
and then in the javascript side you can do
var allcoor = <?php echo json_encode($corar); ?>;

Related

Json decode in javascript

i have encoded my required data in the json object ,but i want to decode the json object into a javscript array, my json encoded object is :
{"product_id":"62","product_quantity":"65"}
however i want to use this json in my java script and want it to be available to a java script array
so if i do :
var arr = new Array()
arr = <?php json_decode('$json_object',TRUE); ?>;
however when i check my page source i get null i.e arr =
how can i assign my json object converted to array to java script array ?
further how to access the json objects from java script array ?
json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).
Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).
Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.
Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
Also note that this JSON:
{"product_id":"62","product_quantity":"65"}
Will transform in to a PHP associative array or a JavaScript object (which is not an array).
So given this PHP:
<?php
$json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
alert(arr.product_id);
</script>
You get this output:
<script>
var arr;
arr = {"product_id":"62","product_quantity":"65"};
alert(arr.product_id);
</script>
Which alerts 62 when run.
You could push the JSON objects into javascript array and iterate through the array, selecting the appropriate fields you need.
Fixed it..
var json = {"product_id":"62","product_quantity":"65"};
var array = new Array();
array.push(json);
for(var i = 0; i < array.length; i++){
console.log(array[i].product_id)
}
Okay so to start off :
the json string generated in PHP can be used in Javascript as an Object. If you declare the variable as an array to start with then it might conflict.
anyway this should work :
<?php
$error_fields_structure = array(
'product_id' => 4531
,'main_product_quantity' => 2
);
$json_object = json_encode($error_fields_structure);
?>
<html>
<head>
<script>
var jsonstring = <?php echo (isset($json_object) ? $json_object : 'nothing here'); ?>
for( var i in jsonstring ){
alert( i +' == ' +jsonstring[i] );
}
</script>
</head>
<body>
</body>
</html>

Getting PHP session array values into Javascript

I have stored array values in PHP session.
Now I want to retreive this array and convert it to javascript aray.
This is how I set PHP session:
var listone = ["one", "two", "three"];
function setSession(listone){
$.get(
"setSession.php",
{listone:listone}
);
}
So if once these values are set and I refresh the page, I check if the session has been set. If set, I want to do something like this:
<?php
session_start();
if(isset($_SESSION['listone']))
{
?>
listone = Array('<?php echo json_encode($_SESSION['listone']) ?>');
<?php
}
?>
When I do this, the 'listone' array is showing me like this:
listone[0] = [
listone[1] = "
listone[2] = o
listone[3] = n
listone[4] = e
listone[5] = "
.... etc
I know I am doing something wrong.
Is it the way I am storing the array in PHP session?
or
Is it the way I am retrieving it back to JS?
Thanks for any pointers. I am willing to dig more if guided properly :)
You may be trying to do one of two things here- either something to do with AJAX, which is expecting a JS response, or you're trying to access a session variable directly in JS.
If you simply wish to switch a PHP variable into a JS readable array, you can do:
json_encode($_SESSION['myarray']);
This would need to be a response readable & interpreted elsewhere by a JS script (e.g. an AJAX response).
PHP session variables arent accessable through JS directly, however, you can construct JS within PHP, wrapping the two together so you use PHP to output JS populated with the data held within your PHP session variable. The key here is the order of the code, and how your JS is structured- i.e. you will probably want to reference a global JS variable so the values are accessible by your other JS- or call a function etc...
So, you could have:
session_start();
if(!isset($_SESSION['myarray'])){
$_SESSION['myarray']=array('one', 'two', 'three');
}
echo "<script type='text/javascript'>
var myJSvariable = new Array();";
foreach($_SESSION['myarray'] as $key=>$value){
echo "myJSvariable[".$key."]=".$value.";";
}
echo "</script>";
Try to change your php file to this or a similar one
<?php
session_start();
$result = array();
if(isset($_SESSION['listone'])) {
$result['listone'] = $_SESSION['listone'];
}
echo json_encode($result);
?>
json_encode translate your array into a json array and you don't need to create a new one.
Plus I would put the required variables into an hash array and return just the json_encode of that array in order to have a cleaner code.

Passing a multidimensional PHP array to javascript

I have an array($my_array) that looks something like:
array(2) {
[25]=>int(10)
[30]=>int(8)
}
I'd like to assign it to a javascript array, but am having difficulties doing it. Any suggestions?
Edit: At first, I thought I could just assign it like a string, but that isn't working:
var photo_limit = $my_array;
I tried also doing a var_dump into my js value.
I'm currently trying to use something like:
for($i=0;$i<count($my_array); $i++){
echo "a[$i]='".$a[$i]."';\n";
}
Thanks.
The best way is to use json_encode. See json_encode reference
Used like this:
<script>
var array = <?php echo json_encode($array)?>;
</script>
Note, hovewer, that you'll receive Javascript object, instead of array. At a glance the only difference is if you have string keys in your array, you'll be able to access them in JS like array.*string key*, i.e. using dot notation.
1: json_encode your PHP array.
2: Decode the JSON string in JavaScript using eval(alternative: jQuery.parseJSON)
<script>
var arr = eval('(<?php echo json_encode($thePhpArray); ?>)');
</script>

How to read php array of string in javascript

var longitudeArray = new Array(<?php $result = count($longitudeArray);
if ($result > 1){
echo implode(',', $longitudeArray);
} else {
echo $longitudeArray[0];
}
?>);
$longitudeArray contain array of number like: $longitudeArray = array(23.54545, 2323.32);
Above script create following javascript array:
var longitudeArray = new Array(12.32444,21.34343,23.5454);
but if i passes string in $longitudeArray like:
$longitudeArray = array('one', 'two');
instead of integer value in $longitudeArray then my javascript array is not creating properly or its not working.
Try
var longitudeArray=<?=json_encode($longitudeArray)?>;
If you pass an array of strings to your code, you will end up without quotes around them in your generated javascript code. You need to add some quotes somehow, something like:
var longitudeArray = new Array("<?php echo implode('","', $longitudeArray);?>");
#Shad, very useful and efficient approach. In the same manner, if one is trying to convert a PHP array to pass back to a JavaScript function (EG: an AJAX callback), that would be accomplished as such:
$some_php_array = array( 'indexA' => 'nice', 'indexB' => 'move' );
json_encode($some_php_array);
Where the PHP data would look as follows in JavaScript:
{"indexA":"nice","indexB":"move"}

PHP array to JS array with jQuery and json_encode

I just want to get my PHP array to a JS array, what am I doing wrong here?
PHP:
// get all the usernames
$login_arr = array();
$sql = "SELECT agent_login FROM agents";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
array_push($login_arr, $row["agent_login"]);
}
$js_login_arr = json_encode($login_arr);
print $js_login_arr; // ["paulyoung","stevefosset","scottvanderlee"]
JS:
var login_arr = "<?= $js_login_arr; ?>";
alert(login_arr); // acn't even get the string in??
var obj = jQuery.parseJSON(login_arr);
Remove the quotes from the embedded PHP in your javascript. The notation is an array literal, and doesn't need quoting (assuming the PHP comment after js_login_arr is the what is printed into the javascript).
An easy way to do it is through delimiting. Take your array (don't use assoc arrays unless you need the field names), implode it into a string delimited by some character that shouldn't be used, say % or something, then in JS just explode on that character and voila, you have your array. You don't need to always use formalisms like JSON or XML when a simple solution will do the trick.
If you want to make php array to JSON you have to do this if $phpArray is actually an array.
var jsJSON = echo json_encode($phpArray)
If you want just to echo and turn to JSON you have to give it like a string:
$phpArray = '{'.$key1.':'.$val1','.$key2':'.$val2.'}';
This will work for sure.

Categories