I have a website that where a user can browse through products in a gallery format. This gallery will be populated using an ajax call that passes the category to a php script which then fetches all the items matching that category and echoes all the item information back. The success function of the ajax call then needs to split the data and insert each items data into its own array that will be used to generate the html to display the item.
I am struggling with the inserting the data into its own array part as the amount of items will vary depending on how many are in the database at the moment.
Here is what I have so far:
The jQuery function:
$('.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 }
}).done(function(data) {
alert('Succes ' + data);
var arr = data.split('#'); // Information split by #
for (int i = 0; i < (arr.length / 4); i++) { // arr.length divided by 4 because each item has 4 pieces of information
// Insert each item into its own array. So the first array will be arr[0], arr[1], arr[2], arr[3]. Second array will be arr[4], arr[5], arr[6], arr[7]
}
}).fail(function(response) {
alert('Fail' + response);
});
});
Here is the php script:
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
$category = $_GET['category'];
$conn = mysqli_connect('localhost', 'root', 'Changde90', 'database');
$rows = mysqli_query($conn, "SELECT * FROM products WHERE category = '".$category."'");
$items = '';
while ($row = mysqli_fetch_array($rows)) {
$itemName = $row[1];
$itemPrice = $row[2];
$itemImage = $row[3];
$itemDescription = $row[4];
$items .= $itemName.'#'.$itemPrice.'#'.$itemImage.'#'.$itemDescription.'#';
}
echo $items;
}
Create the array in php like this :
while ($row = mysqli_fetch_array($rows)) {
$arr[] = $row;
}
echo json_encode(array("data" => $arr));
Then in your javascript just decode the data and use it in your code as you like it. For example :
var arr = $.parseJSON(data);
arr.itemName will return the item name
arr.itemprice will return the item price
Remember you have use the above code inside of $.each()
Hope this helps you.