This is what I have
The JS file:
var loadBtn = document.getElementById('loadButton');
loadBtn.addEventListener('click', fetchProducts);
let quantity = 3;
function fetchProducts() {
quantity = quantity + 3;
var xhr = new XMLHttpRequest;
xhr.open('GET', `php/products.php?quantity=${quantity}`, true);
xhr.onload = function () {
if (this.status == 200) {
var products = JSON.parse(this.responseText);
var output, i;
for (i = 0; i < products.length; i++) {
output += `
<div id="pCard" class="p-card">
<p id="pName" class="p-name">${products[i].item_name}</p>
<p id="pAbout" class="p-about">${products[i].item_description}</p>
</div>
`;
}
document.getElementById('products').innerHTML = output;
}
}
xhr.send();
}
The PHP file:
include 'config.inc.php';
$quantity = $_GET['quantity'];
$sqlFetch = "SELECT id,item_name,item_description FROM items ORDER BY id ASC LIMIT $quantity";
$result = mysqli_query($connection, $sqlFetch);
$products = mysqli_fetch_all($result, MYSQLI_ASSOC);
echo json_encode($products);
I expected, after defining the quantity in the js
file the fetchProducts function
would increment the quantity of products and parse the quantity
through GET
to the php
file. Instead, this is what am getting from products.php
:
Notice: Undefined index: quantity in C:\wamp64\www\simplesites\ss9_ajax\php\products.php on line 7