Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

131
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda