3

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?

Mikey
  • 366
  • 1
  • 4
  • 20
  • try `console.log(data);`, avoid `alert`s –  Aug 27 '14 at 07:37
  • If I do this, it logs the object to the console. I'm still not sure how to access individual elements inside the object though – Mikey Aug 27 '14 at 08:06
  • **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Aug 27 '14 at 08:49

3 Answers3

1

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.

Jhecht
  • 4,407
  • 1
  • 26
  • 44
1

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"] );

}
  • Thank you so much !! Really struggled with this – Mikey Aug 27 '14 at 10:37
  • @Mikey, Just a side note. Since you're going to access the properties by their database field name, consider calling it like `mysqli_query($conn,"..query..",MYSQLI_ASSOC);`. Notice the flag **MYSQLI_ASSOC** to avoid both numeric and assoc fields retrieved and therefore sent. –  Aug 27 '14 at 10:49
  • Okay, will do that as well :) – Mikey Aug 27 '14 at 11:17
0

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])

blagi
  • 26
  • 4