Return PHP array in JSON in AJAX

Asked

Viewed 1,786 times

0

I have the following code:

function atualizaPainelQtdeReservas(){ 
     var dataFiltro = $(".dataFiltro").val();

     $.ajax({  
          url: "crud/painelQuantidadeReservas.php", 
          dataType: 'html',
          data: {dataFiltro:dataFiltro},
          type: "POST", 

         success: function(data){
              $('#resBusca1').html(data[1]);
         },
     });
};

And

 $dataFiltro = $_POST['dataFiltro'];
 $data = implode("-",array_reverse(explode("/",$dataFiltro)));
 $select = "SELECT SUM(numeroPessoas) as total FROM Reserva
            where data = '$data'
            group by hora
            ";
$conexao = conexao();
$PDO = $conexao -> prepare($select);
$PDO -> execute();

$total = array();
while ($obj = $PDO -> fetch(PDO::FETCH_OBJ)){
    $total[]= $obj->total;
}
echo json_encode($total);

SELECT will return data: 9, 6, 2

I want to return in Success the array with the results, but as I did in $('#resBusca1'). html(date[0]) what returns to me is a [

If I do:

 success: function(data){
 for(var i in data) {
     document.write(data[i]);
 }
 },

it returns ["9","6","2"]

Each result (9,6,2) I want to return in an id in html. Any suggestions?

  • You’re using dataType: 'html', you should wear dataType: 'json',.

  • Opa, thanks, solved. And if I need a multiple array, how could I do?

  • You can give an example of this json?

1 answer

0


For multidimensional array reading, you can read on success of AJAX, stipulating of course the dataType: 'json', with the $.each:

success:function(resposta){
   $.each(resposta, function(i, resp){
      // agora é colobar resp.indice que obterá o valor do índice correspondente no array json 
   })
}

Browser other questions tagged

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