Reputation: 85
I am send some data from php by json_encode to javascript. this is the data
[{"albumid":"ASaBFzCtl8","albumname":"anni","type":"3","access":"2","itemcount":"2"},{"albumid":"EmgsZ43ehT","albumname":"testalbum","type":"1","access":"1","itemcount":"0"},{"albumid":"Jf4H4SvFGk","albumname":"test2album","type":"3","access":"1","itemcount":"0"},{"albumid":"k3pacBSmIl","albumname":"testalbumpvt","type":"3","access":"2","itemcount":"0"}]
after enoding in php it is something like that
//json_encode($data);
"[{\"albumid\":\"ASaBFzCtl8\",\"albumname\":\"anni\",\"type\":\"3\",\"access\":\"2\",\"itemcount\":\"2\"},{\"albumid\":\"EmgsZ43ehT\",\"albumname\":\"testalbum\",\"type\":\"1\",\"access\":\"1\",\"itemcount\":\"0\"},{\"albumid\":\"Jf4H4SvFGk\",\"albumname\":\"test2album\",\"type\":\"3\",\"access\":\"1\",\"itemcount\":\"0\"},{\"albumid\":\"k3pacBSmIl\",\"albumname\":\"testalbumpvt\",\"type\":\"3\",\"access\":\"2\",\"itemcount\":\"0\"}]"
i am receiving this in jquery
$.post("demo.php",
{
token:"123456789"
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
what can i do so that i get all data in javascript array i need type value out of it and looking something like that
var typevalue = jsonArray['type'];
// typevalue = 3
Upvotes: 0
Views: 4005
Reputation: 2511
Assuming you have parsed json here's how you loop it:
$.each(data, function(key, album){
console.log(album.type);
});
To grab the first type in the list simply do:
var albumType = data[0].type;
Full solution with parsing:
$.post("demo.php", {
token: "123456789"
},
function (data, status) {
$.each(data, function (key, album) {
alert(album.type);
});
}, "json"); //datatype defined here
Upvotes: 1
Reputation: 11
1stly you can encode the array directly
$sendData = JSON_encode(array(
"albumId"=>"ASaBFzCtl8",
"albumName"=>"anni",
// etc
));
echo $sendData;
2ndly in JS, you can parse the date with JSON_parse
$.post("demo.php",
{
token:"123456789"
},
function(data,status){
var json = JSON_parse(data);
console.log(json.albumId); // or alert
}
);
Upvotes: 0
Reputation: 20753
Sending array from php as-
json_encode($php_array);
Receive the array in js-
var js_array = jQuery.parseJSON(result);
$.each(js_array , function(idx,obj) {
console.log(obj.type);
});
Upvotes: 0