My data table that is loading its body from another file with ajax is giving me the invalid JSON error, but when I check my developer tools under network responses my JSON is valid?
This is my PHP and SQL:
<?php
header('Content-Type: application/json');
$output = array('data' => array());
$query = "SELECT * FROM table";
$stmt = sqlsrv_query($sapconn2, $query);
$x = 1;
while($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)){
$output['data'][] = array(
'col_1' => $x,
'ID' => $row['ID'],
'QuoteID' => $row['QuoteID'],
'CardCode' => $row['CardCode'],
'SlpCode' => $row['SlpCode'],
'SlpName' => $row['SlpName'],
'BandA' => $row['BandA'],
'NewPrice' => $row['NewPrice']
);
$x ++;
}
echo json_encode($output);
?>
This is my JSON thats returned in the browser:
{
"data": [
[1, 138, 25, "000123", "222", "test data", 222, 222],
[2, 144, 25, "000123", "132", "test data", 465, 789],
[3, 160, 25, "000123", "456132", "test data", 5599, 5499],
[4, 171, 25, "000123", "789", "test data", 7897, 989],
[5, 172, 25, "000123", "11111", "test data", 1, 11],
[6, 182, 25, "000123", "132166", "test data", 1323, 133],
[7, 183, 25, "000123", "135456", "test data", 1332132, 13213],
[8, 184, 25, "000123", "1321", "test data", 5643214, 6513]
]
}
EDIT:
var testTable = $("#testTable").DataTable({
processing: false,
serverSide: true,
dataType : 'json',
ajax: "test.php",
columns: [
{ "data": "col_1" },
{ "data": "ID" },
{ "data": "QuoteID" },
{ "data": "CardCode" },
{ "data": "SlpCode" },
{ "data": "SlpName" },
{ "data": "BandA" },
{ "data": "NewPrice" }
]
});
This is what datatable waits for:
{
"data": [
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421"
},
...
]
}
The "data" element is an array of objects, instead you pass an array of array.
You need something like that:
{
"data": [
{ "id": 1, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
{ "id": 2, "second_field": 138, "third_field": 25, "fourth_field": "000123", ... },
]
}
EDITED:
$output['data'][] = array(
'col_1' => $x,
'col_2' => $row['ID'],
'col_3' => $row['QuoteID'],
'col_4' => $row['CardCode'],
'col_5' => $row['SlpCode'],
'col_6' => $row['SlpName'],
'col_7' => $row['BandA'],
'col_8' => $row['NewPrice']
);
When you make a request to a server-side script from DataTables with processing set to true then it sends this data.
When it returns data DataTables expects the data to follow these conventions.
You can either take these into account with your server-side script (there's a good example here.) or choose a different method for adding your data. If you perhaps set processing to false you might find everything just works as you expect.
Hope that helps.
Related
How to get nested pojo result like this one,
object
------object
------object
------------object
------array
This is I got from somewhere I forgot, but it has no code for make this result.
{
"success": true,
"counter": {
"pending": 100,
"rejected": 200,
"completed": 300,
"expired": 400,
"total": 3200
},
"pie_statistics": {
"assigned": 120,
"opened": 212,
"in-progress": 100,
"completed": 320,
"done": 433,
"rejected": 111,
"expired": 332
},
"bar_months":[
"jan",
"feb",
"mar"
],
"bar_pending":[
100,
200,
300
],
"bar_rejected":[
140,
220,
340
],
"bar_completed":[
170,
290,
310
]
}
with my code like this
<?php
require "connection.php";
$query = "SELECT a.kondisi, k.area, COUNT(k.area) AS carea, COUNT(k.nrp) AS cnrp
FROM tb_absens AS a
INNER JOIN tb_karyawans AS k
ON a.nrp = k.nrp
WHERE a.kondisi = 'Sehat'
GROUP BY k.area";
$data = mysqli_query($conn, $query);
$json_array = array();
while($row = mysqli_fetch_array($data)){
array_push($json_array, array(
"success" => true,
"cnrp" => $row["cnrp"],
"area" => $row["area"],
"kondisi" => $row["kondisi"],
));
}
echo json_encode($json_array);
the result of mine like this
[
{
"success": true,
"cnrp": "1",
"area": "Administrator",
"kondisi": "Sehat"
},
{
"success": true,
"cnrp": "2",
"area": "AMK CPBP",
"kondisi": "Sehat"
},..
]
Yeah I know it's somekind old question, with many of questions similiar to. But I have no clue at all. I appreciate any help. Thanks.
If you want to get different json type into single json, you can split query first, and you execute each of query. To get nested object result like this
"counter": {
"pending": 100,
"rejected": 200,
"completed": 300,
"expired": 400,
"total": 3200
},
try execute
while($row = mysqli_fetch_assoc($data)){
$json_arr['counter'][$row['a']] = $row['b'];
}
for nested array
"bar_months":[
"jan",
"feb",
"mar"
]
use this
while($row = mysqli_fetch_assoc($data)){
$json_arr2['bar_months'][] = $row_area['months'];
}
and to merge it to single json you can use
echo json_encode(array_merge($json_arr, $json_arr2));
Hope it can helps
I have a problem with my web service response and i'm not able to fix this problem.
So i want to get a result with letter data in Uppercase, cause after that I don't able to see my informations.
Here this my code on web service :
/**
* #Route("/contact/getContactFilter/{tdlinx}/{soc}", name="contact_getContactFilter")
*/
public function getContactFilter($tdlinx, $soc){
$em = $this->getDoctrine()->getManager("APP_REFERENTIEL");
$contactFilter = $em -> getRepository(CONTACT::class)->findBy(["TDLINX" => $tdlinx,"SOCIETE" => $soc,"ACTIF" => 1]);
$encoders = [new JsonEncoder()]; // If no need for XmlEncoder
$normalizer = new ObjectNormalizer();
$normalizers = [new \App\Utils\DateTimeNormalizer(), $normalizer];
$serializer = new Serializer($normalizers, $encoders);
$jsonObject = $serializer->serialize($arrayUpper, 'json', [
'circular_reference_handler' => function ($object) {
return $object->getId();
}]);
if(!$contactFilter) return new Response(null,204);
else return new Response($jsonObject,200, ['Content-Type' => 'application/json']);
}
And this is my response on Postman and the problem is visible here at third part :
{
"id": 63,
"TDLINX": 257242,
"TYPE": "physique",
"SOCIETE": "B",
"NOM": "Post",
"PRENOM": "Strike",
"COMMENTAIRE": "Test",
"ACTIF": true,
"INFOS": [
{
"id": 52,
"VALUE": "006516451",
"CONTACTID": 63,
"TYPEID": {
"id": 15,
"lIBELLE": "Phone fixe",
"pATTERN": "phone",
"sOCIETE": "B",
"iCON": "local_phone",
"lIST": [],
"iNFOS": [
{
"id": 51,
"VALUE": "034455258",
"CONTACTID": {
"id": 169,
"tDLINX": 257242,
"tYPE": "physique",
"sOCIETE": "B",
"nOM": "Norris",
"pRENOM": "Chuck",
"cOMMENTAIRE": "Test",
"aCTIF": false,
"iNFOS": [
{
"id": 50,
"VALUE": "Directeur adjoint",
"CONTACTID": 169,
"TYPEID": {
"id": 17,
"lIBELLE": "Poste",
"pATTERN": "liste",
"sOCIETE": "B",
"iCON": "business_center",
"lIST": [
{
"id": 12,
"VALUE": "Directeur",
"TYPEID": 17
},
{
"id": 13,
"VALUE": "Directeur adjoint",
"TYPEID": 17
},
{
"id": 14,
"VALUE": "Chef de rayon",
"TYPEID": 17
}
],
"iNFOS": [
50,
{
"id": 53,
"VALUE": "Directeur adjoint",
"CONTACTID": 63,
"TYPEID": 17
}
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
}
},
51
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"TYPEID": 15
},
52
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
}
}
}```
How to fix this problem ?
Please check your database probably you defined id as "id"(first letter in small letter)
I currently have the below json response that the API is returning. I am able to return it using Laravel Eloquent. There are several users and each user has a several receipts. A receipt has types and status. I want to try to get the total sum amount for each receipt that is related to its type and status. I was able to return the below json response using
$this->user->with('receipts')->has('receipts')->get(['id', 'name']);
I have tried using multiple laravel collections methods https://laravel.com/docs/5.8/collections#available-methods But I am still unable to get the desired response.
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"id": 1,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 2,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 100
},
{
"id": 3,
"user_id": 1,
"type_id": 2,
"status": 1,
"amount": 50
},
{
"id": 4,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 5,
"user_id": 1,
"type_id": 2,
"status": 0,
"amount": 30
},
{
"id": 6,
"user_id": 1,
"type_id": 1,
"status": 0,
"amount": 20
},
{
"id": 7,
"user_id": 1,
"type_id": 1,
"status": 1,
"amount": 10
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"id": 9,
"user_id": 2,
"type_id": 1,
"status": 0,
"amount": 20
}
]
}
]
I expect to get this:
[
{
"id": 1,
"name": "kent",
"receipts": [
{
"performance and deleted": 220,
"performance and not deleted": 10,
"project and deleted": 60,
"project and deleted": 50
}
]
},
{
"id": 2,
"name": "allison",
"receipts": [
{
"performance and deleted": 20,
"performance and not deleted": 0,
"project and deleted": 0,
"project and not deleted": 0
}
]
}
]
My main concern is to use laravel collection methods and easy to read code to get my expected result
In this way, I believe you get your expected result with nice readable code.
I'll assume that you have $users variable which contains a list of users in collection (And probably the receipts are already loaded).
// You need to name the keys as you desire. (I can't figure out the labels by the type_id and status numbers).
$statusPair = collect([
'performance and deleted' => [
'type_id' => 1,
'status' => 0,
],
'something' => [
'type_id' => 1,
'status' => 1,
],
'something 2' => [
'type_id' => 2,
'status' => 0,
],
'something 3' => [
'type_id' => 2,
'status' => 1,
],
]);
$data = $users->map(function ($user) use ($statusPair) {
$receipts = $user->receipts;
$sums = $statusPair->mapWithKeys(function ($pair, $statusLabel) use ($receipts) {
$filtered = $receipts;
foreach ($pair as $key => $value) {
$filtered = $filtered->where($key, $value);
}
$sum = $filtered->sum('amount');
return [
$statusLabel => $sum,
];
});
return [
'id' => $user->id,
'name' => $user->name,
'receipts' => $sums->toArray(),
];
});
i think this will help
$user->receipts->sum('amount');
This is the static multidimension array and i converted to json.
$mailmsg = array(
'type'=> 'line',
'data' => array(
'labels' => array("1","2","3","4","5"),
'datasets' => array(array("label"=>"A","fill"=>"false","yAxisID"=>"A","borderColor"=>"#bae755","data"=>array(100, 96, 84, 76, 69)),array("label"=>"B","fill"=>"false","yAxisID"=>"B","borderColor"=>"#55bae7","data"=>array(1, 1, 1, 1, 0)),array("label"=>"C","fill"=>"false","yAxisID"=>"C","borderColor"=>"#e755ba","data"=>array(5, 15, 10, 10, 0)))),
' '=>array("scales"=>array("yAxes"=>array(array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn1"),"id"=>"A","type"=>"linear","position"=>"left"),array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn2"),"id"=>"B","type"=>"linear","position"=>"left"),array("scaleLabel"=>array("display"=>"true","labelString"=>"Prn3"),"id"=>"C","type"=>"linear","position"=>"left")))
));
echo $json = json_encode((object)$mailmsg, JSON_NUMERIC_CHECK);
Result:
{
"type": "line",
"data": {
"labels": ["1","2","3","4","5"],
"datasets": [{
"label": "A",
"fill": "false",
"yAxisID": "A",
"borderColor": "#bae755",
"data": [100, 96, 84, 76, 69]
}, {
"label": "B",
"fill": "false",
"yAxisID": "B",
"borderColor": "#55bae7",
"data": [1, 1, 1, 1, 0]
}, {
"label": "C",
"fill": "false",
"yAxisID": "C",
"borderColor": "#e755ba",
"data": [5, 15, 10, 10, 0]
}]
},
"options": {
"scales": {
"yAxes": [{
"scaleLabel": {
"display": "true",
"labelString": "Prn1"
},
"id": "A",
"type": "linear",
"position": "left"
}, {
"scaleLabel": {
"display": "true",
"labelString": "Prn2"
},
"id": "B",
"type": "linear",
"position": "left"
}, {
"scaleLabel": {
"display": "true",
"labelString": "Prn3"
},
"id": "C",
"type": "linear",
"position": "left"
}]
}
}
}
I need to above static array to change dynamically using foreach.
just pass the reference to the specific data in the array:
foreach($mailmsg['data']['datasets'] as $key => $value){
}
I've got the following JSON array with PHP:
"data": [
{
"RecordID": 1,
"OrderID": "53150-422",
...
},
{
...
},
I do this with:
echo json_encode(array('data' => $users),JSON_PRETTY_PRINT);
Now I want to add metadata to the array like this:
{
"meta": {
"page": 1,
"pages": 1,
"perpage": -1,
"total": 350,
"sort": "asc",
"field": "RecordID"
},
"data": [
{
"RecordID": 1,
"OrderID": "53150-422",
...
},
How to to this? Thanks in advance!
write code this way
<?php
$meta=[ "page"=> 1,
"pages"=> 1,
"perpage"=> -1,
"total"=> 350,
"sort"=> "asc",
"field"=> "RecordID"];
$users= [
"RecordID"=> 1,
"OrderID"=> "53150-422"
];
echo json_encode(array('meta'=>$meta,'data' => $users),JSON_PRETTY_PRINT);
?>