how to build this json in php - javascript

im using php to send a push but my json object isent getting the way i want...
i need my json to be like this :
{
"to": ["xxx"],
"data": {
"title": "dw",
"body": "dw",
"actions": [
{ "icon": "emailGuests", "title": "Candidatar-me", "callback": "app.emailGuests", "foreground": true},
]
}
}
but im getting this instead :
{
"to": "xxx",
"data": {
"title": "dw",
"body": "dw",
"actions": {
"icon": "send.ico",
"title": "EMAIL GUESTS",
"callback": "app.callbackName",
"foreground": true
}
}
}
i am building my json like this :
$fields = array ( 'to' => $row1['fcm_registered_id'] ,
'priority' => "high",
'data' => array("title" =>$titlepost,
"body"=> $msg,
"actions" => array('icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
),
);

Remember that json_encodeconverts non-numeric indexed arrays to objects. There is why you gets objects instead of array of objects. It's enough to wrap this array by another array. Here is fixed code:
$fields = array (
'to' => array( $row1['fcm_registered_id'] ),
'data' => array(
"title" =>$titlepost,
"body"=> $msg,
"actions" => array(
array(
'icon' => 'send.ico',
'title' => 'EMAIL GUESTS',
'callback' => 'app.callbackName',
'foreground' => true
)
)
)
);
And here is working example: http://phpio.net/s/1n0e
Little note: try to use new array syntax: [] than old array()

Related

Yii2 How to pass php array data into highcharts

I am using Yii2 extension miloschuman/yii2-highcharts for charts and get confused passing php array into hightcharts.
My Array Values
Array
(
[Power Electronics] => 14.00
[Introduction to Programming] => 3.92
[Data base Management System] => 3.28
[Object Oriented Analysis and Design] => 1.96
)
Now simply what I want to add this data to my highcharts I am passing above array like my below code.
FROM MY HIGHCHARTS CODE
'series' => [
[
"name" => "Exam Results",
"data" => $course_data,
'dataLabels' => [
'enabled' => true,
'rotation' => -90,
'color' => '#FFFFFF',
'align' => 'right',
'format' => '{point.y:.1f}', // one decimal
'y' => 10, // 10 pixels down from the top
'style' => [],
'fontSize' => '13px',
'fontFamily' => 'Verdana, sans-serif',
],
],
],
I have already try many things but not get any success I wanted output like this charts.
Have you tried to call json_encode function with mentioned array passed as an argument? Here is the code:
<?php
$data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
];
echo json_encode($data);
[EDIT]
You can also try to use SeriesDataHelper feature. There is information about using it in the documentation, here is the link: https://github.com/miloschuman/yii2-highcharts/blob/master/doc/examples/series-data-helper.md#using-numerically-indexed-data
Here is example code:
use miloschuman\highcharts\SeriesDataHelper;
$data = $data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
]
'series' => [
[
"name" => "Exam Results",
"data" => new SeriesDataHelper($course_data, ['0:name', '1:y']),
'dataLabels' => [
'enabled' => true,
'rotation' => -90,
'color' => '#FFFFFF',
'align' => 'right',
'format' => '{point.y:.1f}', // one decimal
'y' => 10, // 10 pixels down from the top
'style' => [],
'fontSize' => '13px',
'fontFamily' => 'Verdana, sans-serif',
],
],
],
According to docs your array has invalid format. It should look like his:
$data = [
['Power Electronics', 14.00],
['Introduction to Programming', 3.92],
['Data base Management System', 3.28],
['Object Oriented Analysis and Design', 1.96],
];
You can fix this with simple foreach:
$newData = [];
foreach ($data as $key => $value) {
$newData[] = [$key, $value];
}

Using Jest to test Jquery that calls PHP ajax

I have a Javascript file with a function I'm trying to test. All the function does is make a jQuery post request to a PHP ajax file (see code)
function loadTeams(clubID){
var data = {
action: 'loadClubTeams',
clubID: clubID
};
return jQuery.post('/ajax/calendar_ajax.php', data);
}
I have a mock set up in my /__mocks__/ dir as such:
<?php
$teams = array(
array(
"Name" => "Team 1",
"ClubID" => 34
),
array(
"Name" => "Team 2",
"ClubID" => 34
),
array(
"Name" => "Team 3",
"ClubID" => 35
)
);
$response = array();
if($_REQUEST['action'] == "loadClubTeams"){
foreach($teams as $team){
if($team['ClubID'] == $_REQUEST['ClubID']){
array_push($response, $team);
}
}
}
return json_encode($response);
Here is my test file:
const assoc_cal = require('../../secure-htdocs/js/templates/association_calendar');
jest.mock('../../secure-htdocs/ajax/calendar_ajax.php');
test("loadTeams returns Teams 1 and 2 when passed clubID 34", () =>{
data = {action: "loadTeams", ClubID: 34};
const expected = [
{
name: "Team 1",
clubID: 34
},
{
name: "Team 2",
clubID: 34
}
];
expect(assoc_cal(data)).toEqual(expect.arrayContaining(expected));
});
But when I run my test, it still tries to call the real calendar_ajax.php file. I'm apparently setting up the mock incorrectly. Can anyone else out with this?

Rendering complex JSON from mysql and use column value as label

I have a table with 1000 records and a corresponding data history of 5 years, including events. The table structure looks like this at the moment:
id|date|reference_id|account_id|dataSet|price|title|type|description
1|2006-01-03|ID00001|1|dataSet01|44.23|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
2|2006-01-03|ID00002|1|dataSet02|62.75|||
3|2006-01-03|ID00003|1|dataSet03|25.95|Dividend|D|Amount: 0.22
4|2006-01-03|ID00004|2|dataSet04|31.81|||
5|2006-01-03|ID00005|3|dataSet05|78.20|||
6|2006-02-01|ID00001|1|dataSet01|45.85|Dividend|D|Amount: 0.30
7|2006-02-01|ID00002|1|dataSet02|59.37||
8|2006-02-01|ID00003|1|dataSet03|27.59|Dividend|D|Amount: 0.26
9|2006-02-01|ID00004|2|dataSet04|34.24|||
10|2006-02-01|ID00005|3|dataSet05|83.42|||
11|2006-03-01|ID00001|1|dataSet01|45.54|Analyst opinion change|A|Upgrade by Bank from Sell to Hold
12|2006-03-01|ID00002|1|dataSet02|60.86|||
13|2006-03-01|ID00003|1|dataSet03|27.04|Downgrade by Bank from Buy to Hold
14|2006-03-01|ID00004|2|dataSet04|36.04|||
15|2006-03-01|ID00005|3|dataSet05|84.32|||
I want to render the data depending on account_id (in this case account_id = 1) to get the following JSON:
{
"data": [{
"date": "2006-01-03",
"dataSet01": "44.23",
"dataSet02": "62.75",
"dataSet03": "25.95"
}, {
"date": "2006-02-01",
"dataSet01": "45.85",
"dataSet02": "59.37",
"dataSet03": "27.59"
}, {
"date": "2006-03-01",
"dataSet01": "45.54",
"dataSet02": "60.86",
"dataSet03": "27.04"
}],
"events": [{
"dataSet01": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}]
},{
"dataSet03": [{
"date": "2006-01-03",
"title": "Analyst opinion change",
"text": "A",
"description": "Upgrade by Bank from Sell to Hold"
}, {
"date": "2006-02-01",
"title": "Dividend",
"text": "D",
"description": "Amount: 0.30"
}, {
"date": "2006-03-01",
"title": "Analyst opinion change",
"text": "A",
"description": "Downgrade by Bank from Buy to Hold"
}]
}]
}
I'm struggling to build the json though. As of right now I'm rendering the data like this:
$query = "SELECT date, price
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
$data = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
$data[] = $row;
}
return json_encode( $data );
Obviously this returns the json with price as label for each record value (price). How should the query look like instead to render the above json example?
$query = "SELECT *
FROM datatable
WHERE account_id = 1
ORDER BY date ASC";
$result = mysql_query( $query );
// Define temporary arrays
$data = array();
$events = array();
while ( $row = mysql_fetch_assoc( $result ) ) {
// Assemble the data grouped by date and dataset
if ( !isset($data[$row['date']]) )
{
$data[$row['date']] = array(
'date' => $row['date'],
);
}
// Inject dataSet in $data grouped by date
if ( !isset($data[$row['date']][$row['dataSet']]) )
{
$data[$row['date']][$row['dataSet']] = $row['price'];
}
// Assemble events grouped by dataSet
if ( !isset($events[$row['dataSet']]) )
{
$events[$row['dataSet']] = array();
}
$events[$row['dataSet']][] = array(
'date' => $row['date'],
'title' => $row['title'],
'text' => $row['type'],
'description' => $row['description']
);
}
// Remove date keys
$data = array_values($data);
return json_encode(array(
'data' => $data,
'events' => $events
));

Data tables server-side formating links

I have a table with tones of records and I need some links inside the table, so the problem is about formatting...
The first row is a link of the name of the patient to his single page and the last row is a collection of links for edit and delete the patient.
The problem:
Now with this code in the first row don't appear the name (row[1]),
appear the surnames (row[2]) but the link is ok (row[0])
In the last row both links are working good, but thickybox is not
working, the link is opened in a new page.
Can somebody help me with that? thank's in advance!!! :)
Server-side processing script:
$columns = array(
array(
'db' => 'id',
'dt' => 0,
'formatter' => function( $d, $row ) {
$links=''.$row[1].'';
return $links;
}),
array( 'db' => 'apellidos', 'dt' => 1 ),
array( 'db' => 'tel_mov', 'dt' => 2 ),
array( 'db' => 'terapeuta', 'dt' => 3 ),
array(
'db' => 'id',
'dt' => 4,
'formatter' => function( $d, $row ) {
$links2='<img src="ima/edit.png" /> | <img src="ima/close.png" />';
return $links2;
}),
);
Javascript:
$(document).ready(function() {
$('#tablet').DataTable({
"language": {
"url": "https://cdn.datatables.net/plug-ins/9dcbecd42ad/i18n/Spanish.json"},
"scrollY": "400px",
"scrollCollapse": true,
"processing": true,
"serverSide": true,
"ajax": "load.php"
});
} );
I got it ;)
For the links names problems:
Just add first column of the table a id data and if you don't need it hide it with options in the javascript ("bVisible": false)
So now the $row[0] is always the id and the $row[1] the name...
For the thickbox problem:
Just add "aoColumns" whith the options an after "fnDrawCallback"
"aoColumns": [
{ "sTitle": "id","bVisible": false},
{ "sTitle": "Nombre" },
{ "sTitle": "Apellidos" },
{ "sTitle": "Móbil","bSortable": false },
{ "sTitle": "Fijo","bSortable": false },
{ "sTitle": "Terapeuta","bSortable": false },
{ "sTitle": "Edición","bSortable": false,"bSearchable": false }],
"fnDrawCallback": function() {
tb_init('a.thickbox');
}
I don't know if is the best way but is working for me ;)

Creating a javascript variable from an JSON file

i have php var same this in index.php file :
<?php
$aoData = '
{ "name": "count", "value": "5" } ,
{ "name": "tbl", "value": "member" } ,
{ "name": "0", "value": "id" } ,
{ "name": "1", "value": "fname" } ,
{ "name": "2", "value": "lname" } ,
{ "name": "3", "value": "username" } ,
{ "name": "4", "value": "mail" }
';
include("main.php");
?>
i need send this php var as js function parameters in main.php and i use json like this:
<input type="button" onClick="run(<?php echo htmlentities(json_encode($aoData)); ?>)"
and i need use this var in load.js as a parameters. my load.js is like this :
function run(data1){
var oTable =$('#example').dataTable( {
aoData.push(**data1**)},
"onblur" : "disable",
"select" : true })}
but this way doesn't work.
It looks like your data is already json_encode()ed in your main PHP file. You should just be able to echo is using htmlentities() to make sure it is attribute-safe.
So run( <?php echo htmlentities( $aoData ); ?> )
Just as a note, what you're doing with json_encode() would work if $aoData looked like:
$aoData = array(
array( 'name' => '', 'value' => '' ),
array( 'name' => '', 'value' => '' ),
array( 'name' => '', 'value' => '' ),
);
json_encode() takes an array/object and turns it into JSON, which is a string that is formatted similarly to how your $aoData is currently.
You shouldn't be hand-coding json in PHP. There are too many potential encoding issues that can develop from this. Make a PHP array and then encode that.
$aoData = array();
$aoData[] = array('name' => 'count', 'value => 5);
...
echo json_encode($aoData);
The data table function needs two parameters. But you are pass one variable to that function.
Look through the documentation of datatable and their input types.
You can use php variable directly on your javascript function its on a same page.
Try to alert the javascript params for check yourself
Your json.encode not handled correctly. Already you have a json string. Then why you need encode
I actually agree with Tyler Carter
you should encode your JSON from a PHP array.
The following example is completely independent and you can see the result in your console
<?php
$aoData = json_encode(array(
array("name" => "count", "value" => "5"),
array("tbl" => "count", "value" => "member"),
array("0" => "count", "value" => "id"),
array("1" => "count", "value" => "fname"),
array("2" => "count", "value" => "lname"),
array("3" => "count", "value" => "username"),
array("4" => "count", "value" => "mail"),
));
?>
<html>
<body>
<input type="button" onclick="console.log(<?=htmlentities($aoData);?>)" value="run"/>;
</body>
</html>

Categories