retrieve json encoded multidimensional array with ajax - php

I successfully (tested) call an ajax request to a php script. This is the portion of code i need to make working:
success: function (response, status) {
$.each(response, function (i, item) {
alert(item.id);
item.id is just...nothing.
This is the generated - json_encoded array by php page:
[
{
"conto": "1"
},
{
"id": "4",
"activity_id": "50",
"path": "Testo/base.png",
"title": "Ffgf",
"descrizione": "Tttt"
},
{
"id": "8",
"activity_id": "50",
"path": "Testo/61FCFUX_IMG_0536.PNG",
"title": "Hggggg",
"descrizione": "Tgg"
}
]
What do I do wrong?
p.s: if you noticed, this is an array merge between two arrays: the first one just reports "conto" in in, the other one is a list generated by fetching elements by database.

Your first array not containing id so you are getting undefined value. Skip first array:
$.each(response, function (i, item) {
if(i==0)
{
alert(item.costo);
}
else
{
alert(item.id);
//Or better to use console
console.log(item.id);
}
});

I believe your issue is with your reference. Since your JSON object contains an array you will need to reference it with subscripts. Try changing item.id to item[i].id. That way as the each function iterates through the array, it can reference the id field in each object.
Edit: Here's working code.
$(document).ready(function (){
var source = '[{"conto":"1"},{"id":"4","activity_id":"50","path":"Testo\/base.png","title":"Ffgf","descrizione":"Tttt"},{"id":"8","activity_id":"50","path":"Testo\/61FCFUX_IMG_0536.PNG","title":"Hggggg","descrizione":"Tgg"}]';
source = JSON.parse(source);
var cellcount = length(source);
for(var i = 0; i < cellcount; i++){
console.log(source[i].id);
}
});
function length(obj) {
return Object.keys(obj).length;
}

Related

Displaying a single array item from JSON in PHP (NODE.JS and EXPRESS API)

I have Express running on a custom node API that breaks down a large JSON into bite sized chunks for mobile usage.
One of the section goes through a mass of items and returns only one of them. However the returned data is still wrapped in [ .. ] which makes working with it tough.
My NODE.JS code snippet that deals with my routed request
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
res.json(with_operatorCode);
});
so if you access the url
http://(domain)3000/ppm/summary/operators/25
the following data is returned
[
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
]
How can I break that object out of the [ .. ] so it is not returned as an array object and only shows as
{
"code": "25",
"keySymbol": "",
"name": "First Great Western",
"Total": "577",
"PPM": {
"rag": "G",
"text": "94"
},
"RollingPPM": {
"trendInd": "+",
"displayFlag": "Y",
"rag": "G",
"text": "97"
}
}
Alternativly, how can I work with the [ .. ] object in PHP? When I am trying to echo it using
$operatorJSON=file_get_contents("operator.json");
$operator=json_decode($operatorJSON);
echo $operator->PPM->text;
It errors if the JSON has the [ ]
I suspect it is being treated as an array object
UPDATE : I tried to flatten the array
app.get('/ppm/detail/operators/:operatorCode', function (req, res) {
var with_operatorCode = ppm.RTPPMDataMsgV1.RTPPMData.OperatorPage.filter(function (item) {
return item.Operator.code === req.params.operatorCode;
});
var obj = arr.reduce(function(x, y, i) {
x[i] = y;
return x;
}, {});
res.json(obj(with_operatorCode));
});
but the object returned is still in [ ]
If i understand correctly , i think the most easy way is use the index to get the element in array
res.json(with_operatorCode[0]);
Of course, the [foo] denotes that it is an array.
You could address the item as [0], but that is more likely to cause an error, if no item exists in the filter:
On the php side:
$operator=json_decode($operatorJSON);
echo $operator[0]->PPM->text;
On the Node side:
res.json(with_operatorCode[0]);
The smarter thing to do would be to handle it as an array:
$operator=json_decode($operatorJSON);
if (is_array($operator) && count($operator))
{
echo $operator[0]->PPM->text;
}
Or, if filter may give you more than one:
$operator=json_decode($operatorJSON);
foreach ($operator as $op)
{
echo $op->PPM->text;
}
Try for this:
function toObject(arr) {
var obj = {};
for (var i = 0; i < arr.length; ++i)
obj[i] = arr[i];
obj rv;
}

Datatable - JSON not being shown of size larger than 4KB

I am using data table to display data returned by a SQL Server 2008 procedure called in Codeigniter via Ajax($POST). Initially I made a very simple procedure with no input parameters, it only returns a list of JSON objects.
Below are my questions and my Codeigniter function returning JSON, AJAX function and JSON structure returned by my Codeigniter function:
1) JSON not returned for chunk larger than 4KB, it simply converts to HTML:
2) What if one of my procedure returns lets say 5000+ record and i want to display it in data table, is my way of doing it right? Or i should use some other best practices:
Codeigniter Function:
public function executeProc()
{
$sqlsrvr = $this->load->database('test', true);
// Get the input values of the procedure
$arr = array();
parse_str($_POST['str'],$arr);
//get Procedure Name
$procName = $_POST['procName'];
$sp ='exec secondProc';
$query = $sqlsrvr->query($sp);//->result();
$jawad = $query->result_array();
$this->output->set_header('Content-type: application/json');
echo json_encode($jawad);
}
AJAX Function
$(document).on('click','#executeProc',function(e){
$('#demo').html('<table cellpadding="0" cellspacing="0" border="0" class="display" id="example"></table>');
e.preventDefault();
var jawad = $( ".jawad" ).serialize();
$.post('<?=base_url();?>command/executeProc',
{str:jawad,procName:$('#procName').val()},
function(html){
//loading data table on return
$('#example').dataTable( {
"data": html,
"columns": [
{ "data": "AppointmentID" },
{ "data": "FirstName" },
{ "data": "LastName" },
{ "data": "AppointmentDate" }
]
} );
});
});
JSON Sample:
[
{
"AppointmentID": "1",
"FirstName": "Test",
"LastName": "test",
"AppointmentDate": "2013-01-12"
},
{
"AppointmentID": "2",
"FirstName": "dfg",
"LastName": "dfg",
"AppointmentDate": "2013-01-01"
}
]
-----AFTER EDIT------
STRANGE BEHAVIOR(JSON tab converts to HTML for larger records)
FOR 40 records that get displayed on data table
FOR records larger then 40 that don't get displayed on data table

how to read multi-levels json format using jquery

i have a json format like
[
{
id: 15,
diemdung: "a"
},
{
id: "16",
diemdung: "b",
khoangcach: "300",
pho: "c",
da: [
{
lancan: "d",
kc: "333"
},
{
lancan: "e",
kc: "322"
}
]
},
...
]
i using php like print json_encode($rows);
and i try to read it at client using jquery like
$.getJSON(url,function(json){
$.each(json,function(key, val){
$.each(this.da,function(){
alert(this.kc);
});
});
});
but it's not working. How i do that? thanks
If your code is otherwise working, you may be getting the following error:
TypeError: obj is undefined
This is because the first object in the outer array does not have a value for the "da" property. Before you try to loop over the array held by the "da" property, you should check if it exists.
Try:
$.getJSON(url,function(json){
$.each(json,function(){
if (this.da) {
$.each(this.da,function(){
alert(this.kc);
});
}
});
});
$.each(json, function(arrayID, arrayVal) {
//alert(arrayVal.id);
$.each(arrayVal.da, function(daKey,daData) {
alert(daData.kc);
});
});
Heres my same SO question a while ago for further code
JQuery $.each() JSON array object iteration
edit to rename some variables to make clearer
For n level hierarchy
var str = '{"countries":[{"name":"USA","grandfathers":[{"gFName":"Steve","grandfathersKid":[{"gFKName": "Linda","kid": [{"name": "Steve JR", "friends": [{"name": "Kriss|John|Martin|Steven"}]}]}]}]}]}';
var obj = jQuery.parseJSON(str);
parseJsonString(obj);
Function :
function parseJsonString(data){
$.each(data, function(index, val){
if($.type(val) == 'object' || $.type(val) == 'array'){
product.parseJsonString(val);
}else{
alert(index + ' - ' + val);
}
});
}

adding array values to jquery graph syntax

I have a an array that has been json encoded from php
The array looks like this(called $jsonGraphData;):
[{"Type":"Category","Name":"games","TotalClicks":"162"},{"Type":"Category","Name":"apps","TotalClicks":"29"},{"Type":"Category","Name":"music","TotalClicks":"28"},{"Type":"Category","Name":"video","TotalClicks":"25"}]
I would like to use the array values in a loop within a jquery function that generates a graph. These are the hard coded values that allows the graph to work:
series: [{
name: 'games',
data: [162]
}, {
name: 'apps',
data: [29]
}, {
name: 'video',
data: [25]
}]
What I would like to do is to use jquery 'each' to loop through the array so that defining the series is dynamic this is what I am trying to achieve:
var totalClicks = $jsonGraphData; (this is the array, the alert works fine).
series: [{
$.each(totalClicks, function(index, val) {
alert('name: ' + val.Name + ' ' + 'data: ' + val.TotalClicks);
//here is where I need the format to be the same as the example above.
});
}]
I lack the knowledge of jquery syntax to achieve this and do not know what to search for on Google.
Try this code
var series = [];
$.each(totalClicks, function(index, val) {
series.push({name: val.Name, data: val.TotalClicks});
});
Or if data should still be an array with only one value in it.
var totalClicks = [{ "Type": "Category", "Name": "games", "TotalClicks": "162" }, { "Type": "Category", "Name": "apps", "TotalClicks": "29" }, { "Type": "Category", "Name": "music", "TotalClicks": "28" }, { "Type": "Category", "Name": "video", "TotalClicks": "25"}]
var series = [];
$(totalClicks).each(function (index, val) {
series.push({ "name": val.Name, "data": [val.TotalClicks] });
});
You don't need to use jQuery for looping through the regular array.
for(var obj in yourArray){
// do whatever you need with it.
alert(obj.Name + " " + obj.TotalClicks);
}

How do I iterate over a JSON array using jQuery/AJAX call from PHP? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Loop through Json object
I have a PHP function, data.php, which fetches JSON data from an external server URL like such:
<?php
$url = "https://dev.externalserver.net/directory";
$content = file_get_contents($url);
echo json_encode($content);
?>
The JSON array retrieved looks like the following:
[
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
]
I'm now trying to write an AJAX call to that PHP function, iterate through the JSON array, and display it in the browser in non-JSON formatting. My AJAX code looks like the following:
$.ajax({ url: 'data.php',
type: 'POST',
dataType: 'json',
success: function(output) {
$.each(output, function() {
$.each(this, function(key, value){
alert(key + " --> " + value);
});
});
}
});
My issue is that code is currently displaying alert boxes that show the individual characters within the array like such: 0 --> [ , 0 --> , 0 --> { ... etc etc
Is there a problem with how I'm passing the data using json_encode(); and dataType: 'json' or does the issue resolve with how I'm iterating through the array?
Thanks.
Other responders missed the sneaky but still obvious bit, that what's coming back from the resource being polled in the PHP is probably already valid JSON, and re-encoding it is causing the browser to interpret it merely as a string. In this case, the javascript never had a chance.
Remove the json_encode() bit in the PHP and just echo what comes back, and see if that doesn't improve things.
I think your problem is the this in the second each. Try:
$.each(output, function(key, value) {
$.each(value, function(key, value){
alert(key + " --> " + value);
});
});
var jsonArray = [
{ "name": "Not configured",
"mac_address": "1111c11c1111",
"online": "false",
"rate": "Not configured" },
{ "name": "Not configured",
"mac_address": "0000c00c0000",
"online": "false",
"rate": "Not configured" }
];
$.each(jsonArray, function() {
for (var key in this) {
if (this.hasOwnProperty(key)) {
console.log(key + " -> " + this[key]);
}
}
});
take a look at this
How do I loop through or enumerate a JavaScript object?

Categories