Php pass array to Javascript - php

I want an array in Javascript, structure like this
$(function()
{
// prepare the data
for (var i=0; i<50000; i++) {
var d = (data[i] = {});
d["id"] = "id_" + i;
d["num"] = i;
d["title"] = "Task " + i;
d["duration"] = "5 days";
}
I want this array to be created through php.
I already have the array there created by for loop
EDITED:
Is the above data in Javascript a multidimensional array, a simple array or a var?
is the structure saved in "d" or in data[i][id],data[i][title],... ?

ie, $data = array('item' => 'description', 'item2' => 'description2');
json_encode($data);
All you need

Use json_encode() to encode the array.
Access PHP variable in JavaScript
That example works with arrays, too.

Related

$.ajax get an object after json_encode($arr) from php, but how to get key and value in jQuery?

1
In PHP:
$arr = array( 10=>"ten", 5=>"five", 2=>"two"); return json_encode($arr);
In JS - $.ajax():
success: function(data){ console.log(data);}
2
What I see in console is :
Object {2: "two", 5: "five", 10: "ten"},
I want to use for(var i=0; i< data.length,i++) but failed.
Finally it works in this way : for(var i in data)
3
My Question: Why the array is sorted? I want the array to keep unsorted.
Anyone helps me?
JSON cannot represent a sparse array, which is what your data would be if it did.
So you get an object instead of an array and the is no standard that says object properties has to sorted in any specific way or not sorted at all.
You can try having your data in 2 arrays
$arr = array( 'indecies'=>array(10,5,2), 'values'=>array("ten","five","two") );
return json_encode($arr);
for(var i=0; i< data.indecies.length,i++){
// do something with
//data.indecies[i]
//data.values[i]
}

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 to pass arrays through JSON php

I'd like to pass arrays through JSON like this:
<?php
for(i=0;i<5;i++) {
$arrayA[i] = "A" . i;
$arrayB[i] = "B" . i;
}
echo json_encode($arrayA,$arrayB);
?>
I know it's not possible, but is there other way to pass dynamicly loaded arrays and read them in javascript after that?
Just put both array in another array.
$returnArr = array($arrayA,$arrayB);
echo json_encode($returnArr);
On JS side just decode with a library of your choice and access the returned array like any normal array.
echo json_encode(array('arrayA' => $arrayA, 'arrayB' => $arrayA));
Just create wrapper for your arrays:
for(i=0;i<5;i++) {
$arrayA[i] = "A" . i;
$arrayB[i] = "B" . i;
}
$arrayC = array($arrayA,$arrayB);
echo json_encode($arrayC);
On jQuery side:
$.getJSON('ajax/yourPhpFile.php', function(data) {
$.each(data, function(key, val) {
// each `val` is one of the arrays you passed from php
});
});
You can use AJAX to load up a script that will return a PHP generated array. If you're using jQuery, you call it using either $.get() or $.getJSON(). You can read up on PHP JSON manual here http://php.net/manual/en/book.json.php and on jQuery .getJson() function here http://api.jquery.com/jQuery.getJSON/

JavaScript: Remove keys from json object

Example output from PHP:
{
"RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
"RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
}
How can I use Backbone.js or jQuery to only have:
[
{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
]
If it's easier to use PHP to edit the JSON, then so be it.
Well, in PHP it would be easy, just use array_values() on the initial array so that it 'forgets' the array indexes (which by the way, is what 'RootName_X' is called in your case:
$newvalue = array_values( (array)$value );
echo json_encode($newvalue);
In javascript, it's a bit trickier, but it would be on the lines of:
var newvalue = [];
for(var root in value)
newvalue.push(value[root]);
The question title is was a bit confusing since these are certainly not tags.
No need for jquery or Backbone:
var obj = {
"RootName_0":{"Id":1,"ValId":1,"Value":"Colour","Text":"Blue"},
"RootName_1":{"Id":1,"ValId":2,"Value":"Colour","Text":"Red"}
};
var colors = [];
for(var key in obj){
colors.push(obj[key]);
};
The value you want is now in the colors array.
Using ES5 (modern browsers) you could do:
Object.keys(received).map(function(key) {
return received[key];
});
Basically, converting the object into an array of its keys, then replacing each key with the value.
In javascript, if myFirstVar contains the initial object, then do:
mySecondVar = [ myFirstVar.RootName_0, myFirstVar.RootName_1 ];
Once the JSON has been parsed, do it using jQuery's jQuery.map, and borrowing the global Object function...
var arr = $.map(obj,Object);
EDIT:
If you do it in JavaScript, you should be aware that the objects may not remain in their original order.
You can remedy this if the RootName_n keys are sequential, and you know the n of the last key.
var last_key = 20;
var arr = [];
for(var i = 0; i <= last_key; i++)
arr.push( obj['RootName_' + i] );

placing a multi-dimensional array into Javascript from PHP using JSON

My php script sends back a JSON encoded string.
I'm just lost on how to actually use the array now it sits nicely in Javascript?
The end goal is to loop through the the multi-dimensional array in JavaScript to extract values (prices)...
I've managed to get JavaScript to receive the encoded string (tested by printing it onto screen), but I'm not sure how I can actually use the array, or how I would loop through it like I would in PHP..
I basically need to do the JavaScript equivalent to this PHP code
foreach ($array as $item => $value){
foreach ($value as $item2 => $value2){
//peform action on $value2;
}
}
Thanks for any help.
Oz
Assuming you've called the variable arrayFromPhp, you can use a simple nested for loop:
for(var i = 0, l = arrayFromPhp.length; i < l; i++) {
for(var j = 0, l2 = arrayFromPhp[i].length; j < l2; j++) {
var value = arrayFromPhp[i][j];
//Do stuff with value
}
}
Using jquery, you can iterate on a json object like that:
$.each(obj, function(key, value) {
if ($.type(value) == "object") {
$.each(value, function(key, value) {
// value would be $value2 here
})
}
});
Also, if you get a json encoded string from PHP, you can use http://api.jquery.com/jQuery.parseJSON/ to get a json object
var obj = jQuery.parseJSON(stringFromPhp);
You can also directly use $.getJSON() (http://api.jquery.com/jQuery.getJSON/) to automatically get the json object in the callback.
edit: a parenthesis was missing.

Categories