A point was raised (since deleted) about just sending the one variable as opposed to sending a JSON object.
Trial and error, but here is an alternative using jQuery and a FormData object to send the one property QueryFilter
HTML/JS
<body>
<h1>Products</h1>
<output id='products'></output>
<script
src='https://code.jquery.com/jquery-3.7.1.min.js'
integrity='sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo='
crossorigin='anonymous'
></script>
<script>
// sample request object
const request = { term: 'Ipad' };
// create a FormData object and append the QueryFilter property
const formData = new FormData();
formData.append('QueryFilter', request.term);
$.ajax({
url: './server/test.php',
type: 'POST',
// disable Jquery's default behaviour for contentType and processData
contentType: false,
processData: false,
dataType: 'json', // return type
data: formData,
success: function (data) {
const output = document.querySelector('#products');
// Just for an example output the returned data
output.insertAdjacentHTML(
'afterbegin',
`<pre>${JSON.stringify(data, null, 2)}</pre>`
);
}
});
</script>
</body>
PHP
<?php
// Sample products
$products = [
0 => [
'id' => 1,
'name' => 'Ipad',
'text' => 'All-screen design with 10.9-inch Liquid Retina display delivers an amazing viewing experience',
'url' => './my-products/ipad',
],
1 => [
'id' => 2,
'name' => 'Iphone',
'text' => 'An all‑new 48MP Main camera enables super‑high‑resolution photos and 2x Telephoto. Durable colour‑infused back glass and aluminium design. ',
'url' => './my-products/iphone',
],
2 => [
'id' => 3,
'name' => 'Ipad Pro',
'text' => 'All-screen design with 12-inch Liquid Retina display delivers an amazing viewing experience',
'url' => './my-products/ipad-pro',
],
];
if($_SERVER['REQUEST_METHOD'] == 'POST') {
// search term to lower case
$queryName = strtolower($_POST['QueryFilter']);
$results = [];
foreach($products as $product) {
if (str_contains(strtolower($product['name']), $queryName)) {
array_push($results, $product);
};
}
echo json_encode($results);
}
Output (search term ‘Ipad’)
Products
[
{
"id": 1,
"name": "Ipad",
"text": "All-screen design with 10.9-inch Liquid Retina display delivers an amazing viewing experience",
"url": "./my-products/ipad"
},
{
"id": 3,
"name": "Ipad Pro",
"text": "All-screen design with 12-inch Liquid Retina display delivers an amazing viewing experience",
"url": "./my-products/ipad-pro"
}
]