Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

130
Views
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

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);
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

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]}` )
        })
    })
about 4 years ago · Juan Pablo Isaza Report

0

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(
about 4 years ago · Juan Pablo Isaza Report

0

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)
        })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!