Mikey
Mikey

Reputation: 396

Ajax Accessing a multidimensional array returned from PHP in JSON

I am using an ajax get method to return some information from my database. The ajax method sends whichever category has been selected to a php script which fetches all the rows in my products table and adds these rows to a variable called $arr. $arr is a multidimensional array containing each item and the details of that item.

I am really struggling with trying to access this information once it is returned to the ajax success function. Here is my ajax function with the alerts I have tried to use to see the data contained in the 'data' object:

$('.category').click(function() {

    var category;

    if ($(this).hasClass('Shirts')) {
        category = 'shirts';
    }
    if ($(this).hasClass('Hats')) {
        category = 'hats';
    }
    if ($(this).hasClass('Acc')) {
        category = 'acc';
    }

    $.ajax({
        type: 'GET',
        url: 'galleryfetch.php',
        data: { 'category' : category },
        dataType: 'json',
        success:  function(data) {


            // alert(data);  Alerts '[object Object]'
            // alert(data[0]); Alerts 'undefined'
            // alert(data[0].ID); Console Error: Cannot read property 'ID' of undefined
            // alert(data.array[0].ID); Console Error: Cannot read property 'ID' of undefined
        }
    });
});

The function finds out which category has been clicked and then sends that to the galleryfetch.php script that grabs all the rows from the database with that category and returns them in JSON format as shown below:

if ($_SERVER['REQUEST_METHOD'] == 'GET') {

    $category = $_GET['category'];

    $conn = mysqli_connect('localhost', 'root', 'Chan&', 'clothing');   

    $rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");



    while ($row = mysqli_fetch_array($rows)) {

        $arr[] = $row; 
    } 

    echo json_encode(array('data' => $arr));
}

If I use Firebug to debug the code I can see that the right data is definitely contained in the 'data' object: enter image description here

How can I access this data?

Upvotes: 3

Views: 13923

Answers (3)

blagi
blagi

Reputation: 26

You are returning array which have a key 'data' receiving it javascript parameter/variable with same name. You shoud check javascript data.data, and it is an array:

console.log(data.data[0])

Upvotes: 0

user1299518
user1299518

Reputation:

Based on the image posted, you're receiving an array called data, that consists of 4 objects. The problem is that inside of each of these objects you're messing numeric indices and assoc indices. I would try this:

success:  function(data) {

   // accessing all the properties
   for(var x in data["data"]) {
      for(var y in data["data"][x]) {
         if (y=="ID") {
            alert( "ID of "+x+" is: "+data["data"][x][y] );
         }
      }
   }

   // or simply
   alert( data["data"][0]["ID"] );

}

Upvotes: 1

Jhecht
Jhecht

Reputation: 4435

I believe the problem is that you're putting the data in a key called data. So THIS should output your expected results.

$.ajax({
        type: 'GET',
        url: 'galleryfetch.php',
        data: { 'category' : category },
        dataType: 'json',
        success:  function(data) {

              console.log(data.data[0]);
        }
    });

EDIT: If you're using Google Chrome, I recommend the Postman add-on. It's a good way to mimic AJAX calls, especially if you're using less common HTTP methods like PUT and DELETE. I used it a lot in attempting to develop my own API.

Upvotes: 1

Related Questions