Hi beemybold,
This is expected behavior due to the security system on IF, if you attempt to use non-browser tools like CURL or Postman, it won’t work. The i=1 appended query parameter shows this behavior.
To correctly test your page, you should use a browser as your page is expecting a GET request anyways. Your browser can understand the security system and will redirect to your ajax request without issues. What matters here is that your page can produce a result that works out a json response instead of an HTML.
I’ve revised your code as follows for better debugging insights and easier reading:
<?php
header('content-Type: application/json; charset="utf-8"');
if(!array_key_exists('productId', $_GET)){
echo json_encode([
'error' => 'Product ID is missing.',
]);
exit(400);
}
$product_id = trim($_GET['$product_id']);
if(empty($product_id)){
echo json_encode([
'error' => 'Product ID is empty.',
]);
exit(400);
}
if(!!!preg_match('/^[a-zA-Z0-9\-]$/', $product_id)){
echo json_encode([
'error' => 'Product ID is invalid.',
]);
exit(400);
}
$query = sprintf('SELECT * FROM `products` WHERE `product_id` = "%s"', mysqli_real_escape_string($conn, $product_id));
$result = mysqli_query($conn, $query);
if (!$result) {
echo json_encode([
'error' => 'Product ID is not found.',
]);
exit(404);
}
$data = mysqli_fetch_assoc($result);
if(sizeof($data) === 0){
echo json_encode([
'error' => 'Product ID is not found.',
]);
exit(404);
}
$data['coverImageUrl'] = 'path_to_default_image';
if(array_key_exists('product_cover', $data) && !empty($data['$product_cover'])){
// make an attempt to check if the file exists here
$data['coverImageUrl'] = sprintf('admin_area/book_cover/%s', $data['product_cover']);
}
$data['product_stars'] = intval($data['product_rate']);
echo json_encode($data);
exit(200);
Meanwhile, there’s one more encoding that will involve in your website display - your code’s encoding. Even if you set the meta charset to UTF-8, if the file itself is not then things will still go south. To change that, use Notepad++ and change the file encoding to UTF-8 (without the DOM).
Also mysqli_real_escape_string
is no longer considered secure, and you should seek solutions like PDO, or use framework query methods.
P.S. I’ve read another post on this forum saying that websites that have been mentioned here was DDoSed, and I also find yours suspended due to hit limits, you might want to reach out to support for solution on that one to continue solving the matter here.
Cheers!