Using JSON returned via PHP in Javascript

Solution:
You can create a new array of the data you want to return to the JS. For example, inside your function you could change your code to look like this
$Json = json_decode($JsonContents);
$output = [];
for ($x = 1; $x <= 10; $x++) {
$hint = [];
$hint['brand'] = $Json->hints[$x]->{'food'}->{'brand'};
$hint['label'] = $Json->hints[$x]->{'food'}->{'label'};
$output[] = $hint;
}
return $output;
You can then return this data like so
echo json_encode(getFoodFromAPI($ingr));
Your JS would look like this:
foodSearched.forEach(function(hint) {
console.log('Brand is ' + hint.brand + ' and label is ' + hint.label);
});
You are close to achieving your goal, you just need to return only the 'broken down' data of the API request to the JS HTTP request. At the moment, you are doing the correct PHP logic of breaking down only the data you want to return to the JS, but you are using$JsonRec = json_encode($Json);
which is sending back all of the API request rather than your PHP logic.
Hope this helps.
Here is a working example for you to just test
# Eggs
$response = json_decode(file_get_contents('https://api.edamam.com/api/food-database/parser?ingr=egg&app_id=47971bbd&app_key=15ddd5fb6a552c59762e2dc7093d5f85'));
$output = [];
for ($x = 1; $x <= 10; $x++) {
$hint = [];
$hint['brand'] = $response->hints[$x]->{'food'}->{'brand'};
$hint['label'] = $response->hints[$x]->{'food'}->{'label'};
$output[] = $hint;
}
header('Content-Type: application/json');
var_dump(json_encode($response)); # Here is what your JS would see
die();
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: the browser (or proxy) sent a request that this server could not understand.
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.