How to read php array of string in javascript - php

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"}

Related

Store value of php array variable to javascript array variable

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); ?>;

Create a Javascript array from a PHP array

I am having trouble converting from a PHP array to a Javascript array and then accessing the value. I have tried JSON encoding and decoding.
PHP:
$simpleArray= [];
$childProducts = Mage::getModel('catalog/product_type_configurable')
->getUsedProducts(null,$_product);
foreach($childProducts as $child) { //cycle through simple products to find applicable
$simpleArray[$child->getVendor()][$child->getColor()] = $child->getPrice();
var_dump ($simpleArray);
}
Javascript:
var simpleArray = <?=json_encode($simpleArray)?>;
//..lots of unrelated code
for(var i=0; i < IDs.length; i++)
{
console.log(simpleArray);
//which color id is selected
var colorSelected = $j("#attribute92 option:selected").val();
console.log('Value of color selected is ' + colorSelected);
$j('.details'+data[i].vendor_id).append('<li class="priceBlock">$'+simpleArray[i][colorSelected]+'</li>');
}
Edit:
I have gotten rid of the simpleArrayJson declaration in the php and changed the first line of the javascript.
The is no reason for you to json_decode() the value you are trying to output. Just echo it directly:
var simpleArray = <?= $simpleArrayJson ?>;
This will output a javascript object literal.
Remove from the php.
$simpleArrayJson=json_encode($simpleArray, JSON_FORCE_OBJECT);
here you are converting the php array into a json string.
Change in the javascript
var simpleArray = <?= json_encode($simpleArray, JSON_FORCE_OBJECT); ?>;
Here you are just outputting the sting. previously you where doing this
var simpleArray = <?=(array) json_decode($simpleArrayJson)?>
which after json_decode was returning an array, which you where casting to an array which then was cast to a string by the <?= so what ended up going to your browser was something like:
var simpleArray = Array;
try a for in loop.
for( item in data ) {
console.log(data[item]);
}
this is because json has keys that match the indexes of the array that was json_encoded, instead of necessarily 0->n indexes.
Edit thanks to comments changed data.item to data[item]

How can I pass an array in a url to be retrieved by javascript?

I am trying to pass an array in a url so I tried this:
?question_id=10&value=1&array=["Saab","Volvo","BMW"]
This didn't work (didn't think it would, but it's a start).
It's a key and value array anyway so I needed something like this:
&array[28]=1&array[9]=1&array[2]=0&array[28]=0
But that didn't work either
in jquery try this
var arr = [1, 4, 9];
var url = '/page.php?arr=' + JSON.stringify(arr);
window.location.href = url;
If you want to pass an array, you just have to set the different parts of the array in the URI like
http://example.com/myFile.php?cars[]=Saab&cars[]=volvo&cars[]=BMW
So you get your formated array in $_GET['cars']
print_r($_GET['cars']); // array('Saab', 'Volvo', 'BMW')
To get such a result in javascript you can use this kind of code
var cars = ['Saab', 'Volvo', 'BMW'],
result = '';
for (var i = cars.length-1; i >= 0; i--) {
results += 'cars[]='+arr[i]+'&';
}
results = results.substr(0, results.length-1); // cars[]=BMW&cars[]=Volvo&cars[]=Saab
Try to pass like this
?question_id=10&value=1&my_array=Saab,Volvo,BMW
and you can get like
<?php
$my_array = explode(',',$_GET['my_array']);
?>
or you can try like this
$aValues = array('Saab','Volvo','BMW');
$url = 'http://example.com/index.php?';
$url .= 'aValues[]=' . implode('&aValues[]=', array_map('urlencode', $aValues));
You may also try this:
?arr[]="Saab"&arr[]="BMW"
Using the jQuery getUrlParam extension I can get url variables very easily
or in PHP
var_dump($_GET);

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>

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