I have written a function in PHP which takes product information and user’s desired calories information from a database and puts all of the information in an array. Afterwards it’s encoded in JSON. Then the PHP file is used in a Javascript .html file where it should take the information I just said about from the PHP file and outputs the linear program results. The problem is that the .html file with Javascript in it returns an error in the console and a white page (screenshot).
The PHP file output is shown in the screenshot. I took the output and pasted it in a JSON validator, which shows that it’s valid, so I don’t see the issue here.
Any suggestions?
PHP(part):
// Add the product data to the products array
$products[] = [
'name' => $productRow['product_name'],
'price' => $price,
'calories' => $energyRow['energy_value'],
'UserCalories' => $userCaloriesRow['calories'],
];
}
// Output the products array as a JSON string
header('Content-Type: application/json');
echo json_encode($products, JSON_UNESCAPED_UNICODE);
$mysql->close();
return $products;
}
fetchProductsFromDatabase();
?>
Javascript:
<script src="https://unpkg.com/[email protected]/prod/solver.js"></script>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
// Initialize the products and calories arrays
var products = [];
var calories = 0;
// Make an AJAX request to the PHP script that fetches the products and user's desired calories from the database
$.ajax({
url: 'fetchProductsFromDatabase.php',
success: function(response) {
// The response is a JSON object, so we need to parse it to get the products array and user's desired calories
var data = JSON.parse(response);
products = data.products;
// Set up the linear programming problem
var lp = new LinearProgramming(0, LinearProgramming.MAXIMIZE);
// Set up the constraints
var caloriesConstraint = {};
for (var i = 0; i < products.length; i++) {
caloriesConstraint[i] = products[i]['calories'];
}
lp.addConstraint(caloriesConstraint, LinearProgramming.EQUAL, calories);
// Set up the objective function
var priceObjective = {};
for (var i = 0; i < products.length; i++) {
priceObjective[i] = products[i]['price'];
}
lp.setObjective(priceObjective);
// Solve the linear program
var result = lp.solve();
// Print the results
for (var i = 0; i < products.length; i++) {
console.log(products[i]['name'] + ': ' + result[i]);
}
console.log('Total cost: ' + lp.getObjectiveValue());
},
error: function(jqXHR, textStatus, errorThrown) {
// There was an error with the request
console.log(jqXHR.responseText); // Output the response from the server
console.log(textStatus); // Output the error type
console.log(errorThrown); // Output the exception object, if available
}
});
</script>
2
Answers
you need to stringify the JSON before parsing, something like:
JSON.parse(JSON.stringify(response));
Best regards,
The parameter passed to the
success
callback in jQuery’sajax
method has already been parsed. It is not the string of JSON returned by the PHP, it is the result of reading that string of JSON into an ordinary JS object.In short,
JSON.parse
has already been run before it gets to your code.So instead of this:
You just want this:
The reason you get the error you do is that
JSON.parse
expects a string (a string of JSON data), but you’re passing it an object (the one jQuery has passed you). JavaScript "helpfully" turns the object into the string'[Object object]'
, and passes it toJSON.parse
.