Am trying to fetch and alert id and name records from database using Javasript fetch API.
My issue is that nothing is alerted as the alert is empty.
I Think there is an issue with this line of code
response.json().then(
.
Here is the sample of json that is return by database
[{"id":"5","name":"moore Lizzy"}]
here is the fetch API Javascript
fetch("http://localhost/record/rec.php", {
"method": "GET",
}).then(
response => {
response.json().then(
data => {
console.log(data);
data.forEach((r) => {
alert(r.id);
alert(r.name);
});
}
)
})
here is the php code
//connect db
$id = "5";
$name = "More Lizy";
$result_arr[] = array(
"id" => $id,
"name" => $name
);
echo json_encode($result_arr);
>Solution :
The syntax above is not quite correct. You are chaining the .next() directly to the response.json() – ie response.json().then( where it should be more like the following (slightly abbreviated ) where the .next() is bound to the entire previous next() portion that returns the JSON
fetch( '/record/rec.php' )
.then( r=>r.json() )
.then( json=>{
Object.keys( json ).forEach(k=>{
alert( `${k} - ${json[k]}` )
})
})