Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]}` )
        })
    })
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading