Failure to use JSON on INTEL XDK

Asked

Viewed 78 times

0

I’m making an application on INTEL XDK, in which I need to connect to the database. I created PHP to return with JSON and on Intel, I made the function to return such data. But the application is not returning anything, and as I never did anything in this area, I decided to come here for help. Codes :

JSON.PHP

<?php
    header("Access-Control-Allow-Origin: *");
    header("Content-type: application/json; charset=UTF-8");

    $conecta = pg_connect("host=localhost port=5432 dbname=**** user=****** password=******");
    $sql = "select * from oi";
    $resultado= pg_query($conecta, $sql); 

echo '{"produto":}';
$saida = "[";

while($r = pg_fetch_array($resultado))
{
    if($saida != "["){$saida.= ", ";}
    $saida.= '{"Produto":"'.$r["nomeprod"].'"}';

}
$saida.="}}";
echo $saida;

        ?>

App.js

$(document).ready(function(){
$.ajax({
    type:"GET",
    url:"http://200.145.153.172/bruno_pereira/TCC/json.php",
    dataType:"json"
}).done(function(data){
        var mostra = "";
        $.each(data.produto, function(i,x){
            mostra+= "<li>"+x.Produto+"</li>";
        });
$("#result").html(mostra);        
            });
});
  • hello! First, you are running the page from the localhost ? Otherwise it will not show anything at all. I also don’t know if this is the case, but to turn the array into JSON, you could use the function json_encode .

  • So, I use Winscp to host everything on a machine from my college.. In this case this machine (200.145.153.172

1 answer

0

Hello,

Try to change the php to call the function json_encode to do encoding automatically, so you don’t need to mount JSON manually:

PHP

$conecta = pg_connect("host=localhost port=5432 dbname=**** user=****** password=******");
$sql = "select * from oi";
$resultado= pg_query($conecta, $sql); 

$r['dados'] = $resultado; 
echo json_encode($resultado);

    ?>

And showing if the request succeeds:

JS

$(document).ready(function(){
$.ajax({
  type:"GET",
  url:"http://200.145.153.172/bruno_pereira/TCC/json.php",
  dataType:"json"
    }).done(function(data){
         var mostra = "";
         for (i=0; i< data.dados.length;i++){
           mostra+= "<li>"+data.dados[i].nome_do_campo_desejado+"</li>";
           /* esse nome do campo desejado deve ser o nome de algum campo desejado que tenha 
              sido pesquisado no SELECT do PHP */
         }



$("#result").html(mostra);        
        });
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.