I have a PHP array, like that:
$myArray = array('key1' => value1, 'key2' => value2);
I am converting it to JSON using this code:
$js = json_encode($myArray);
Now in my JavaScript code I want to access the JS array (object?) by its keys, key1 for example, but it doesnt work, the result is always undefined.
Thanks!
Try this
var json = 'yourjsonstring',//'{"key1":"value1","key2":"value2"}'
var obj = JSON.parse(json);
alert(obj.key1);
Try this code
function parseJSON(jsonString){
return eval("(" + jsonString + ")");
}
var object = parseJson(StringFromPhp);
You can get mykey like:
object.key1 // value1
First, you parse the JSON. There are different options to do that, but for example:
var parsedData = JSON.parse(your_data);
And then you access to the key you're looking for. The following is an "associative" way to access to an array (check this out).
alert (parsedData.your_key);
Good luck!
Related
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]
Hey guys i really need help with this. i pass this json object to php..
var x = {};
x.xt = {};
x.xt.id = id;
x.xt.to = foo;
somearray.push(x);
convert object to json:
$.toJSON(x);
json string:
[{"x":{"xt":"9","to":"2"}}]
them i post this:
$.post(
"temp/sop.php",
{ xa: somearray},
function(data){
console.log("response - "+ data);
});
server side:
$xtj = $_POST["xa"];
$encodedArray = array_map(utf8_encode, $xtj);
$asnk = json_decode($encodedArray);
This returns:
string(4) "null"
and this:
$asnk = json_encode($xtj);
returns:
null
the data base it is set to:
UTF8
also when i test if it is an array, comes back true..
any idea how to solve this? thanks
also server side:
$xtj = $_POST["xa"];
$asnk = json_decode($xtj);
this returns:
NULL
$.toJSON(x) does not do the conversion in-place; it returns the JSON, and you're just discarding it. You need this instead:
$.post(
"temp/sop.php",
{ xa: $.toJSON(somearray) },
// ...
});
Then, on the PHP side, you won't want array_map as it's not going to be an array until you decode the JSON:
$xtj = $_POST["xa"];
$encodedArray = utf8_encode($xtj); // I'm not sure you need this, by the way.
$asnk = json_decode($encodedArray);
try using
if(get_magic_quotes_gpc()) $xtj = stripslashes($xtj);
to lose the excessive escaping before trying to decode.
What you are doing is you are converting to json string in JS ($.toJSON()).
And then in PHP you are again trying to convert to json string (json_encode()).
And you are using array_map() on something that is not an array but a string. (Try echo $_POST["xa"]; to see the contents of it.)
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>
Here is my code:
var var_ids = new Array();
var i = 0;
jQuery("select").each(function() {
var_ids[i] = jQuery("option:selected",this).val();
i++;
}
var $data = {
action: "do_something",
var_ids: var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
And in my php:
$ids = mysql_real_escape_string(trim($_POST['var_ids']));
exit(print_r($ids));
And it just returns garbage...So my question is how to pass an array via AJAX to post php?
Thank you.
Most likely you get unexpected results because you apply string-related functions trim and mysql_real_escape_string to array $_POST['var_ids']
As long as it is just an array of integers - the only mysql sanitize you need is casting to int:
$ids = array_map('intval', $_POST['var_ids']);
print_r($ids);
$_POST['var_ids'] is an array in your example on the PHP side. You can only call trim and mysql_real_escape_string on strings not arrays. Try this in php:
$postData = isset($_POST['var_ids'])?$_POST['var_ids']):null;
if(is_array($postData)){
foreach($postData as $key=>$value){
$postData[$key] = mysql_real_escape_string(trim($value));
}
}
Viola, $postData is now a PHP array with trimmed and escaped values.
It's in the docs about 1/4 of a way down titled pass arrays of data to the server
var var_ids = new Array('10','12','13');
var $data = {
action: "do_something",
'var_ids[]': var_ids,
};
jQuery.post(doajax.ajaxurl, $data, function(response) {
alert(response);
});
Make it json_encoded array ... And then You can json_decode() the array properly.
You'll have better luck converting the array to a JSON object (Javascript Object Notation) and sending it that way.
Javascript JSON Instructions
JSON PHP Reference
You can either post each of the items with the key items[], then you could access the array as $_POST['items'] or you can serialize the array, send it and unserialize in PHP (JSON.stringify and PHP json_decode).
I've got a PHP array and echo that into javascript with json encode, i need to do it this way because it's going to be very dynamic. This is the code it echo's:
{"notempty":true}
And i use this to, convert it to javascript:
var myarray = eval('(' + json + ')');
For some reason it creates an object instead of an array and for that reason i cant use .length or a for loop.
Does someone know what im doing wrong here?
Thanks
You're trying to treat an Object like an Array, and an Object is not an Array, it is an Object.
Any time you see {} in JSON, that means "What is contained within these hallowed brackets is a dynamic object". When you see [], that means "Behold! I am an Array" (there are notable exceptions to this one: jQuery does some special work with to make itself look like an array).
So, in order to iterate through an Object, you'll want to use for... in.
// eval BAD unless you know your input has been sanitized!.
var myObj = JSON.parse('{"notempty":true}');
// personally, I use it in for... in loops. It clarifies that this is a string
// you may want to use hasOwnProperty here as sometimes other "keys" are inserted
for( var it in myObj ) console.log( "myObj["+it+"] = " + myObj[it] );
{} is an object, which contains one attribute named notempty. If you want an array, it'd have to be
[{"notempty":true}]
which is an array with a single element at index 0, which is an object with the single attribute 'notempty';.
By default, if you use encode an assoc array in php, it will become a js object when you decode. In order to have it be an array, you need to make it an array in php:
PHP:
$arr = "['notempty','notempty2','notempty3']";
Otherwise, you should convert it to an array in JS, but that seems to me a waste since looping through the object in javascript is so much easier:
Javascript:
var arr = new Array();
for(var i in obj) arr[i] = obj[i];
You can use jQuery to parse it into an array like this:
var p = [];
$.each(jsonData, function (key, val) {
p.push([val.propertyOne, val.propertyTwo]);
});
I am presuming of course that you want to parse JSON, not an array or any other string.