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);
CodePudding user response:
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]}` )
})
})
CodePudding user response:
Adding return to the codeline here also solved the issue. lastly, I also ensured that there is no white spacing in the code.
return response.json().then(
CodePudding user response:
You can also do it this way:
fetch('https://jsonplaceholder.typicode.com/posts', {"method": "GET",})
.then(async (response) => {
const data = await response.json();
console.log("data: ", data)
})