0

I do an ajax call and I get the data back from the controller in this form.

Array
(
[0] => stdClass Object
    (
        [cat_id] => 2
        [title] => Clothes
        [description] => Clothing for men and women
        [active_coupon_counter] => 0
        [store_id] => 1
    )

[1] => stdClass Object
    (
        [cat_id] => 17
        [title] => Designer
        [description] => ;description
        [active_coupon_counter] => 0
        [store_id] => 1
    )

[2] => stdClass Object
    (
        [cat_id] => 24
        [title] => Fashion
        [description] => ;description
        [active_coupon_counter] => 0
        [store_id] => 1
    )

)
Array

This might seem foolish, but I cannot figure out how on earth would I access the cat_id and title properties in each of the arrays!

Any help, guys?

Thanks.

Sreenath S
  • 1,269
  • 1
  • 14
  • 21

4 Answers4

0

you can just use object notation for accessing them:

array[0].cat_id
// returns 2

UPDATE

The returned format from your server has to be JSON, it should look like this:

[
    {
        "cat_id": 2,
        "title": "Clothes",
        "description": "Clothing for men and women",
        "active_coupon_counter": 0,
        "store_id": 1
    },
    {
        "cat_id": 17,
        "title": "Designer",
        "description": ";description",
        "active_coupon_counter": 0,
        "store_id": 1
    },
    {
        "cat_id": 24,
        "title": "Fashion",
        "description": ";description",
        "active_coupon_counter": 0,
        "store_id": 1
    }
]
epoch
  • 16,396
  • 4
  • 43
  • 71
0

You appear to be getting a PHP var_dump or print_r of the data. This is not something that is convenient to parse.

I'm not aware of any JavaScript parser for the format, so you might have to write one from scratch. The question Tutorials for writing a parser with Javascript should give you guidance on that subject.

You would be better off editing the server side script to return the data in a more reasonable format such as JSON or XML.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
-1

It seems like you are using JSON to send and receive data.

So you can access the array object and use:

yourArrayObject[indexYouWantToAccess].cat_id
Bardo
  • 2,470
  • 2
  • 24
  • 42
  • 1
    "It seems like you are using JSON to send and receive data." — The data in the question looks nothing like JSON! – Quentin Oct 01 '12 at 10:01
  • Can you put the code where you receive your data on js from the controller? – Bardo Oct 01 '12 at 10:02
-1

Are you using mysql_fetch_object to get data from the database? Try using mysql_fetch_assoc or mysql_fetch_array.

Also, the response doesn't seem to be a valid json response, as json_encode works properly on both mysql_fetch_object and mysql_fetch_assoc/array.

web-nomad
  • 6,003
  • 3
  • 34
  • 49