JS looking for PHP JSON return

1

I'm starting to use JSON and AJAX and am having a hard time fetching the generated JSON in php for JS. This all in Intel XDK.

In php it looks like this:

if ($_GET['acao'] == 'buscaorcP'){

   $qryOP = mysql_query("select * from orcamento_cab where status = 'P'");

   $retOrcP = mysql_num_rows($qryOP);

   if ($retOrcP > 0){

        while ($linOP = mysql_fetch_object($qryOP)){

           $numOrc = $linOP -> numero;
           $dataOrc = $linOP -> data_e;
           $validOrc = $linOP -> data_v;
           $totOrc = $linOP -> total;

           $arrayJ = array(
               "numero" => $numOrc, 
               "data" => $dataOrc,
               "validade" => $validOrc,
               "total" => $totOrc

           );

          $json =  json_encode ($arrayJ);

And in JS it looks like this:

  function BuscaOrcP() {
    $.ajax({
        type: "get",
        dataType: 'json',
        url: $server+"conecta.php",
        data: "acao=buscaorcP",
        success: function(data){
            var orcamentos = (data);

           $.each(orcamentos, function(i, x){
             show += "<l1>Numero: " +x.numero+" Data: "+x.data+"</li>";
           });
            $('#numero_orcP').html(show);
        }
   });
}

In this situation JS does not search anything, but if I change the dataType to 'html' it looks for the JSON but when I pass the return to a variable it's with undefined.

UPDATE: I was able to resolve this problem by reporting the header in php. Now I've created a new function in JS to fetch a JSON from another function in PHP and it's giving the same error as before. With dataType: 'json' does not fall into success, but if it changes to html it falls.

    
asked by anonymous 17.11.2016 / 22:44

2 answers

1

Add the JSON header at the top of the page where Json will be displayed:

header('Content-Type: application/json');
    
17.11.2016 / 22:48
0

Try the following:

if ($_GET['acao'] == 'buscaorcP'){
 $qryOP = mysql_query("select * from orcamento_cab where status = 'P'");
 $retOrcP = mysql_num_rows($qryOP);
 if ($retOrcP > 0){
   $arrayJ = mysql_fetch_assoc($qeyOP))
   echo json_encode($arrayJ);

mysql_fetch_assoc already transforms the query into an associative array. And echo in json will cause you to get right return $ data in js.

    
23.11.2016 / 15:18