PHP-JSON query

0

After your comments I can obtain them in the following way:

<?php

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

$id = $_POST['id'];

$packing = PackingListData::getPackingList($id);
$arr = array();   
foreach ($packing as $pack) {
                $arr[] = array(
                    "data"=>array(  
                                    'id'=>$pack->id,
                                    'referencia' =>$pack->referencia,
                                    'estilo'=>$pack->estilo,
                                    'bultos'=>$pack->bultos,
                )
              );

}
echo  json_encode($arr);

 ?>

Here it shows in my console.log (data):

And my function js where I try to show that data:

function obtenerPacking(id){

    $.post("index.php?action=getPackingList",{id:id},function(data){

        console.log(data);

        var table = $("#tblListado").DataTable({
                "ajax":{
                    "method":"POST",
                    "dataType":"json"
                    "url";""
                },
                "colums":[
                        {"data":"id"},
                        {"data":"referencia"},
                        {"data":"estilo"},
                        {"data":"bultos"},
                        ]

            });

    })


}

and it generates a conflict from $ .post with my url, how can I add my argument.

    
asked by Ever 20.02.2018 в 20:35
source

1 answer

0

At each iteration of your loop you are printing the output of json_encode . This is received by javascript as

{"foo1":"bar1"}{"foo2":"bar2"}

That is not valid json. What you should do is put all the rows in an array and then print the output of the json_encode:

$arr = array();   

foreach ($packing as $pack) {

// Añado una fila al array
$arr[] = array( 'id'=>$pack->id,
                'referencia' =>$pack->referencia,
                'estilo'=>$pack->estilo,
                'bultos'=>$pack->bultos,

              );

}
// imprimo sólo cuando terminé de iterar
echo  json_encode($arr);

This will print

[{"foo1":"bar1"},{"foo2":"bar2"}]

that is a valid json array.

    
answered by 20.02.2018 / 23:02
source