JS seeking return JSON PHP

Asked

Viewed 210 times

1

I’m starting to use JSON and AJAX and I’m having a hard time fetching the JSON generated in php for JS. That’s all in Intel XDK.

In php this way:

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’s 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 the JS does not look for anything, but if I change the dataType to 'html' it looks for the JSON but when I pass the return to a variable it gives with indefinite.

UPDATE: I was able to solve this problem by informing header php. I have now created a new function in JS to fetch a JSON from another function in PHP and is giving the same error as before. With dataType: 'json' doesn’t fall in the Success, but moves to html falls.

2 answers

1


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

header('Content-Type: application/json');

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 query into an associative vector. And echo in json will make sure you get the return $data in js.

  • I made this adjustment, but he only pulled the last query record. I checked one more in the new code and saw that it was a mouse of mine. Vlw by force.

Browser other questions tagged

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