hyphen
hyphen

Reputation: 967

Valid JSON, but can't display elements of array

I've been working on this for quite a while, and I've read TONS of posts on SO trying to figure out how I need to do this, and I can't seem to get it to work. I'm thinking it must be some aspect of the way I've coded things. So downvote away, but hopefully some kind soul will help me out.

I've tested using jsonlint, which comes back valid. I'm getting a response from the server with the values, I just can't seem to get anything in the browser other than when I just alert(response);. I need to be able to access the value of "cat_id_PK" and the other elements separately to loop through and display them in html table cells.

JSON:

{
"income": [
    {
        "cat_id_PK": 14,
        "cat_name": "test1",
        "cat_amount": "100.00"
    },
    {
        "cat_id_PK": 15,
        "cat_name": "test2",
        "cat_amount": "200.00"
    },
    {
        "cat_id_PK": 34,
        "cat_name": "test3",
        "cat_amount": "300.00"
    },
"expense": [
    {
        "cat_id_PK": 14,
        "cat_name": "tes41",
        "cat_amount": "400.00"
    },
    {
        "cat_id_PK": 15,
        "cat_name": "test5",
        "cat_amount": "500.00"
    },
    {
        "cat_id_PK": 34,
        "cat_name": "test6",
        "cat_amount": "600.00"
    }
]
}

PHP

    $array = array(
        'income'    => $income,
        'expense'   => $expense,
        'recurring' => $recurring
    );

    echo json_encode($array);

JQUERY

var request = $.ajax({
    type: "POST",
    url: 'inc/functions.php',
dataType: "JSON",
    data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
     //for each element put values in <td></td> tags.
});

Upvotes: 0

Views: 318

Answers (2)

nnnnnn
nnnnnn

Reputation: 150010

"I've tested using jsonlint, which comes back valid."

No it doesn't, not for the JSON you've shown which has an error: it is missing a closing ] after the } and before the comma on the line before "expense" : .... But perhaps that's just a typo in your question given that you're generating the JSON with json_encode() (which wouldn't produce an error like that).

" I just can't seem to get anything in the browser other than when I just alert(response);"

So you are getting a value of some sort back then.

" but if I just alert response[0], it will return just the first character of the JSON array."

Yes, that's because response is a string - the raw string containing JSON, where what you want is to parse that string to get an object. Except that you don't have to do this manually because jQuery will do it automatically once you add dataType:"json" to your $.ajax() options.

"I actually was missing the datatype on this one, but even after adding it in, no matter what I try, I'm getting [Object:Object] or undefined. I'm literally doing nothing more than alert(response);"

Once you add the dataType:"json" the response parameter will be an object, which when you try to alert will correctly display as [object Object]. If you use console.log(response) then in your browser's console you'd see the actual object. You'd get undefined if you try to access a property that doesn't exist.

"I need to be able to access the value of cat_id_PK and the other elements separately to loop through and display them in html table cells."

Your response object has two properties, income and expenses, both of which are arrays of object. So use response.income to access the first array of objects, and response.expenses to access the second array of objects. The first income item is response.income[0] and the property you asked about is response.income[0].cat_id_PK. So you can use a for loop, or use $.each() to iterate over the array and do something with each .cat_id_PK property:

var request = $.ajax({
    type: "POST",
    url: 'inc/functions.php',
    dataType: "json",
    data: {action: "display_categories", cur_month:cur_month}
});
request.done(function(response){
  //for each element put values in <td></td> tags.
  var tr = $("<tr></tr>");
  // using traditional for loop for income items
  for(var i = 0; i < response.income.length; i++) {
    $("<td></td>").text(response.income[i].cat_id_PK).appendTo(tr);
  }
  tr.appendTo("#idOfTableHere");
  var tr = $("<tr></tr>");
  // use equivalent jQuery $.each for expense items
  $.each(response.expenses, function(i, v) {
    $("<td></td>").text(v.cat_id_PK).appendTo(tr);
  });
  tr.appendTo("#idOfTableHere");
});

The code I've shown creates new td elements in each loop, appending them to new table rows, and then after each loop the new row is appended to a table that I've assumed already exists on your page with id="idOfTableHere".

Upvotes: 1

Mr.G
Mr.G

Reputation: 3559

try this you miss dataType:

var request = $.ajax({
    type: "POST",
    url: 'inc/functions.php',
    data: {action: "display_categories", cur_month:cur_month},
    dataType:"json",
});
request.done(function(response){
     //for each element put values in <td></td> tags.
});

Upvotes: 0

Related Questions