How to get data from json array in JavaScript? - php

I have php function, that returns array to JavaScript like this:
$data['first'] = 10;
$data['second'] = 20;
echo json_enocde($data);
In JavaScript the returned value is named response. I need to display the values and tried like this after reading about json:
alert("First: " + response.first + " Second: " + response.second);
But this code only shows undefined values in places of response.first and response.second.
If I write alert(response), then I get answer:
{"first":"10","second":"20"}
This means, that JavaScript is getting the information.
How can I get the values separately from the json encoded array?
Regards

Use JSON.parse() to turn the JSON string into a JavaScript object.

Looks like you still have the JSON string, and not parsed it to an JS object. Use JSON.parse:
var jsonString = '{"first":"10","second":"20"}'; // from whereever
var obj = JSON.parse(jsonString);
alert("First: " + response.first + " Second: " + response.second);
alert(obj); // should now be "[object Object]"

use eval like (NOT RECOMMENDED)
var res = eval(response); //as you can see people are against it so I am editing the answer
USE
JSON.parse()
OR if you use jquery
jQuery.parseJSON(response);

Related

PHP Array as JavaScript - accessing the JavaScript elements by key?

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!

javascript objects to json string to php array -> POST

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.)

merge values of unique keys of json string

i have a json output code like this:
{"a":{"p1":"1"},"a":{"p2":"2"},"b":{"b1":"b2"}}
how to convert it to below using javascript or jquery or php ?
{"a":{"p1":"1","p2":"2"},"b":{"b1":"b2"}}
EDIT:
i generate json code by this code:
parts2.push('"'+$(this).attr('alt')+'":{"'+$(this).attr('title') + '"' + ":" + '"'+$(this).attr('value') + '"}' );
however $(this).attr('alt') maybe repeated in loop and i want to prevent duplicate key and instead append value to that key
Each property of an object is supposed to have a unique key name. If you try to parse JSON with duplicate key names, only the last occurring value is used, so it isn't possible to parse this with the native JSON.parse and still expect data to be preserved.
As per your edit, you can prevent the duplicates from ever occurring:
var obj = {};
if typeof obj[$(this).attr('alt')] == "undefined"
obj[$(this).attr('alt')] = {};
obj[$(this).attr('alt')][$(this).attr('title')] = $(this).attr('value');
parts2.push(JSON.stringify(obj));
You should merge the value before you generate the JSON string or you have to implement a JSON parser yourself to parse your JSON.
In http://www.ietf.org/rfc/rfc4627.txt?number=4627:
The names within an object SHOULD be unique
Instead of stringing the pseudo-JSON, just create an object, fill that, and stringify the object when you send it:
var parts = {};
$('.foo')each(function()
{//the loop, here parts is being filled
parts.[$(this).attr('alt')] = parts.[$(this).attr('alt')] || {};//initialize to object if property doesn't exist
parts.[$(this).attr('alt')] = [$(this).attr('title')] = $(this).attr('value');
});
//make JSON:
partsJSON = JSON.stringify(parts);
//{a:{p1:foo,p2:bar},b:{p3:foobar}} or something

Parsing a JSON string to array, not object

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.

send array using jquery

i have a variable $visitRecord->getReferallist() which get the list of doctors in an array . i need to send the array to a php file and do foreach action in php file.. how do i send this array variable in the jquery . This code did not work.
function seekOpinion()
{
var queryUrl = "<?php echo $this->url(array('controller' => 'consultant', 'action' =>'opiniondoclist'));?>";
$.post(queryUrl,{referal:'<?php echo $gotreferal; ?>',visitId:'<?php echo $gotvisitId; ?>',referalList:'<?php echo $visitRecord->getReferallist(); ?>'},function(data)
{
$('.opiniondoclistData').html(data);
});
document.getElementById('opiniondoclistDiv').style.display = "";
}
Your problem is that you're working with an Array in PHP.
echo $visitRecord->getReferallist(); // Returns array of referrals.
When you cast the array to a string by echo'ing it (because echo outputs strings) then you get the text "Array".
In order to send this over the wire(from javascript via AJAX ($.post)) you will need to convert your referral list into a string. One method is serialization. You can convert your array into a "stringable format" using the serialize() function. www.php.net/serialize.
When this is received from PHP in the AJAX request you can convert your "stringable formatted" array back into a pure array using the unserialize() function. www.php.net/unserialize.
Your code should change from
$visitRecord->getReferallist();
to
serialize($visitRecord->getReferallist());
Then when it's received you should change your code from
$referrals = $_POST['referalList']; // Stringable version of the array
to
$referrals = unserialize($_POST['referalList']); // Pure PHP array
Use Serialize() to transform your array into a string, send it , then use unserialize() to get it back into an array in php;
Serialize()
I think you can use json_encode() to encode the array as a string that jquery will be able to read back as a javascript array
EDIT: sorry I didn't read your question properly, I see that you don't want to read the array in javascript, but in PHP so probably serialize() and unserialize() is better than json_encode() assuming that it escapes properly for use with javascript.
var sendData = 'referal=<?php echo $gotreferal; ?>&visitId=<?php echo $gotvisitId; ?>&referalList=<?php echo implode('-', $visitRecord->getReferallist()); ?>';
$.post(queryUrl, sendData,function(data) { //etc
Then the receiving script can (in addition to any necessary sanitization):
$referalList = explode('-', $_POST['referalList']);
Don't forget to addslashes to all the variables you are echoing if necessary
PHP will automatically create an array variable from a query string, or posted data, which contains a "[]" at the end of the name. For example, you can do a jQuery load call as follows to pass an array to PHP.
$('#target').load('index.php?foo[]=a&foo[]=b');
On the PHP side, you will have an array called foo in $_GET
<?php
echo 'I have ' . $_GET['foo'][0] . ' and ' . $_GET['foo'][1];
?>
jQuery's AJAX functions, e.g. $.post, $.get and $.ajax can pass javascript arrays like this in their data sections - just be sure to name the variable with a "[]" at the end so that PHP knows how to handle it.
I found a solution on this problem...
Use this function in your javascript...
function js_array_to_php_array (a)
{
var a_php = "";
var total = 0;
for (var key in a)
{
++ total;
a_php = a_php + "s:" +
String(key).length + ":\"" + String(key) + "\";s:" +
String(a[key]).length + ":\"" + String(a[key]) + "\";";
}
a_php = "a:" + total + ":{" + a_php + "}";
return a_php;
}
a is the array you passed in this function
then.. on your php where you get the return array of this function write this code...
$my_array = unserialize(urldecode(stripslashes($_COOKIE['php_array'])));
// print_r ($my_array);
Hope it helps...

Categories