Home  >  Q&A  >  body text

How to correctly alert database records using Fetch javascript API and php

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);

P粉898107874P粉898107874179 days ago392

reply all(2)I'll reply

  • P粉478835592

    P粉4788355922024-04-04 11:28:02

    Adding return to the line of code here also solved the problem. Finally, I also made sure there were no whitespace in the code.

    return response.json().then(

    reply
    0
  • P粉466290133

    P粉4662901332024-04-04 09:31:10

    The above syntax is not quite correct. You link .next() directly to response.json() - i.e. response.json().then( , where it should be more like below (slightly abbreviated), where .next() is bound to the entire previous next() part

    of the returned JSON
    fetch( '/record/rec.php' )
        .then( r=>r.json() )
        .then( json=>{
            Object.keys( json ).forEach(k=>{
                alert( `${k} - ${json[k]}` )
            })
        })

    reply
    0
  • Cancelreply