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

124
Visualizações
Output PHP already encode to json, and send to javascript to be json, not working

I'm do output with json_encode to sending to javascript, with this code.

<?php

    include "Connection.php";

    $syntax_query = "select * from product";

    $thisExecuter = mysqli_query($conn, $syntax_query);

    $result = array();

    while($row = mysqli_fetch_assoc($thisExecuter)){
        
        array_push(
            $result,
            array(
                "id"       => $row["product_id"],
                "name"        => $row["product_name"]
            )
        );
    }

    echo json_encode($result);

    ?>

so output show like this,

[{"id":"121353568","name":"Baju Casual - Black"},{"id":"556903232","name":"Tas LV - Red"},{"id":"795953280","name":"Sword - Wood"},{"id":"834032960","name":"Scooter - Iron Plate"}]

and code javascript like this

function showHint() {
    const xmlhttp = new XMLHttpRequest();
    xmlhttp.onload = function() {
        var obj = this.responseText;
        
        document.getElementById("txtHint").innerHTML = obj.id;
    }
  xmlhttp.open("GET", "Download.php");
  xmlhttp.send();
}

so obj.id its not working, output show undifined.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

Maybe you need a JSON.parse in the response, something like JSON.parse(this.responseText).

And also I can see the result is an Array so you will need to iterate obj

obj.forEach(item => { 
  document.getElement("txtHint").innerHTML = item.id;
});
        
about 4 years ago · Juan Pablo Isaza Relatório

0

I use ajax calls when I want to call a Php file and get a response from the same as below to try once that as I have shown. Before moving with Ajax you must need jquery to be imported into the calling file.


If Jquery is imported then ignore the steps


Here are steps,

  1. Go to the link https://code.jquery.com/jquery-3.6.0.min.js copy whole content (use ctl+A to select whole content and ctl+C to copy)
  2. Open a new file in the current project folder and paste the copied content (use ctl+V to paste) save it as 'jquery-3.6.0.min.js'
  3. Import the js file in the HTML file in script tag as shown '

Now, this is the ajax example to call the PHP file and to get a response

function showHint() {
//since you have used GET method I have used here GET but You can use POST also here 
 $.ajax({
    url: 'Download.php',
    type: 'get',
//if any value you want to pass then uncomment below line
//    data: {'name_to_pass':'value'}, 
//the variable can be accessed in the php file by 'name to pass' under $_GET['name_to_pass'] or $_POST['name_to_pass'] based on type
    success: function(res)
    {
      //  open DevTool console to see results
      console.log(JSON.parse(res));
    }
    });
}
Hope this will help you out, thank you

about 4 years ago · Juan Pablo Isaza Relatório

0

you should define the response type as json

header('Content-Type: application/json; charset=utf-8');

echo json_encode($result);
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