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:
How can I access this data?