I'm trying to get the alert ID and name records from the database using Javasript fetch API.
My problem is that since the alerts are empty, there aren't any alerts.
I think there is something wrong with this line of code
response.json().then(
. This is an example of json returned by the database
[{"id":"5","name":"moore Lizzy"}]
This 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); }); } ) })
This is the php code
//connect db $id = "5"; $name = "More Lizy"; $result_arr[] = array( "id" => $id, "name" => $name ); echo json_encode($result_arr);
Adding return to the line of code here also solved the problem. Finally, I also made sure there were no whitespace in the code.
The above syntax is not quite correct. You link
of the returned JSON.next()
directly toresponse.json()
- i.e.response.json().then(
, where it should be more like below (slightly abbreviated), where.next()
is bound to the entire previousnext()
part