I am having a very strange issue creating a piechart in Flot with data from PHP.
It seems to be drawing incorrectly, and I can't figure out why.
My PHP code (for testing) is:
echo json_encode(
'[{ label: "Series1", data: 10},
{ label: "Series2", data: 3},
{ label: "Series3", data: 9},
{ label: "Series4", data: 7},
{ label: "Series5", data: 8},
{ label: "Series6", data: 17}]'
);
My JS file is:
$.ajax({
type:'GET',
dataType:"json",
url:'../phpfile.php',
success: function(data) {
console.log(data);
$.plot($("#piechart"),data,{
series: {
pie: {
show: true
}
}
});
}
});
The consol log shows:
[{ label: "Series1", data: 10},
{ label: "Series2", data: 3},
{ label: "Series3", data: 9},
{ label: "Series4", data: 7},
{ label: "Series5", data: 8},
{ label: "Series6", data: 17}]
Which I thought was the correct format for flot...
But it graphs like this:
Does anyone have any ideas?
I believe your JSON currently is invalid, at the moment, you're trying to parse an JSON String, into a JSON String (If you get what I mean!) Currently, when I echo out from the PHP end with your echo'ed json_encode(), I'm provided with:
"[{ label: \"Series1\", data: 10},\r\n{ label: \"Series2\"]"
Furthermore, I would use PHP Arrays to encode JSON, like below:
<?php
$arr = array(
array(
"label" => "Series1",
"data" => 10
),
array(
"label" => "Series2",
"data" => 3
),
array(
"label" => "Series3",
"data" => 9
),
array(
"label" => "Series4",
"data" => 7
),
array(
"label" => "Series5",
"data" => 8
),
array(
"label" => "Series7",
"data" => 17
)
);
echo json_encode( $arr );
?>
PHP json_encode() does accept mixed variable types, but it's most popularly used with PHP arrays.
With the above, I'm able to construct the PIE chart successfully:
Related
I'm using Yajra Laravel Datatables for my data display with serverside ajax loads, to prevent long loads on large amounts.
Now I want to color single TD in a row depending on the status (and other options)
I found that I can easily add parametes to the whole row, depending on options:
->setRowAttr([
'style' => function($item){
return $item->disabled ? 'background-color: #ff0000;' : 'background-color: #00ff00;';
}
])
And this produces me:
But I don't need to color the whole row, only the Bookings TD (in this case) since a different color will be applied for the Active statuses + another one for Room groups, like this:
How can this be accomplished?
PS: I'm using Laravel 5.3 with Datatavles 6
Ok, solved this myself after reading this documentation
http://datatables.net/release-datatables/examples/advanced_init/row_callback.html:
First I added additional columns before Datatables make() call, since the original get overwritten with language outputs, like this:
->addColumn('active', function ($item) {
return $item->disabled ? 0 : 1;
})
->editColumn('disabled', function ($item) {
$item->disabled ? t('No') : t('Yes');
})
Then I added check to JS part right after data call:
serverSide: true,
ajax: {
url: ...,
type: "get"
},
columns: [
...
{data: 'disabled', name: 'disabled'},
...
],
createdRow: function ( row, data, index ) {
...
if ( data['active'] == 1 ) {
$('td', row).eq(5).addClass('success');
} else {
$('td', row).eq(5).addClass('danger');
}
...
},
Pls refer
php:
DataTables::of($query)
->addColumn('stylesheet', function ($record) {
return [
[
'col' => 11,
'style' => [
'background' => '#080',
],
],
[
'col' => 12,
'style' => [
'background' => '#c00',
'color' => '#fff',
],
],
];
});
javascript:
DataTable({
columns: [...],
createdRow: function (row, data, dataIndex, cells) {
if (data.stylesheet) {
$.each(data.stylesheet, function (k, rowStyle) {
$(cells[rowStyle.col]).css(rowStyle.style);
});
}
},
})
Result:
I need to change yii gridview filter to auto search(not autocomplete). for example I have an item name :StackOverflow. for this I need to type stack then press tab/enter to get the results. if I enter Sta the items will display which items start with letters sta(without press tab/enter keys).help me.Thank you
Hi please use below widget
<input type="hidden" name="formula_formula" id="formula_formula" value="">
<?php
$this->widget('zii.widgets.jui.CJuiAutoComplete',
array(
'name'=>'tff',
'source'=>'js: function(request, response) {
$.ajax({
url: "'.$this->createUrl('youraction').'",
dataType: "json",
data: {
term: request.term,
name: "treatment_formula_formula",
pk : "tff_id"
},
success: function (data) {
response(data);
}
})
}',
'htmlOptions'=> array('placeholder'=>'Formula List', 'class' => 'form-control auto_comp_search'),
'options' => array(
'autoFocus' => true,
'showAnim' => 'fold',
'minLength' => '0',
'select'=>'js:function( event, ui ) {
$(ui).hide();
$("#formula_formula").val(ui.item.id);
}'
),
));
?>
the problem here is the dataTables pagination is not working
this is the script i created that outputs json from the database
include( "../database.php" );
$q = $dbh->prepare("SELECT r.studid, r.firstname, r.middlename, r.lastname, r.Enrolling, c.courseid,c.code, s.status,s.dateapproved,s.approvedby FROM pcc_registration r, pcc_courses c, pcc_studentsubj s WHERE c.courseid= r.Enrolling AND s.studentid=r.studid AND r.status=? AND s.status=? GROUP BY r.studid");
$q->execute(array(1,2));
$rows = array();
$i = 1;
while ($r = $q->fetch(PDO::FETCH_NUM, PDO::FETCH_ORI_NEXT, PDO::FETCH_COLUMN)){
$rows[] = array(
"DT_RowId" => "row_".$i,
"reg" => array(
"studid" => $r[0],
"firstname" => $r[1],
"middlename" => $r[2],
"lastname" => $r[3],
"course" => $r[6],
"dateapproved" => $r[8],
"approvedby" => $r[9]
),
);
$i++;
}
$rt = (STRING) $q->rowCount();
$data = array(
"draw" => 2,
"recordsTotal" => $rt,
"recordsFiltered" => $rt,
"data" => $rows
);
echo json_encode($data);
and this is the javascript that outputs the json encoded data to the page
(function($) {
$(document).ready(function() {
$('#dataTables-example').DataTable( {
processing: true,
serverSide: true,
ajax: {
url: "includes/php/approvedSched.php",
type: "POST"
},
"deferRender": true,
columns: [
{data: "reg.studid"},
{data: "reg.lastname"},
{data: "reg.firstname"},
{data: "reg.middlename"},
{data: "reg.course"},
{data: "reg.dateapproved"},
{data: "reg.approvedby"},
{data: "reg.studid"},
],
tableTools: {
sRowSelect: "os",
aButtons: [
// {sExtends: "editor_edit", editor: editor},
// {sExtends: "editor_remove", editor: editor}
]
}
} );
});
}(jQuery));
any answer or solution to this problem is appreciated =)
http://datatables.net/manual/server-side
http://coderexample.com/datatable-demo-server-side-in-phpmysql-and-ajax/
this links is a better help for custom server side with mySQL
Where is the problem exactly? Is it just the DataTable pagination, or is it related with the MySQL query? I mean, does it show the rows and the problem is just the pagination, or it doesn't show anything at all?
I had some issues 'transferring' the query result from php to js as JSON (I'm a complete web programming noob), but DataTables' pagination didn't gave me any problem...
$(document).ready(function () {
output = "";
$.ajax({
url: 'getevents.php',
data: { ufirstname: 'ufirstname' },
type: 'post',
success: function (output) {
alert(output);
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,basicWeek,basicDay'
},
editable: true,
events: output
});
}
});
});
I have code like this and if I copy the text verbatim out of my alert box and replace
events: output
with
events: [{ id: 1, title: 'Birthday', start: new Date(1355011200*1000), end: new Date(1355011200*1000), allDay: true, url: 'http://www.yahoo.com/'},{ id: 2, title: 'Birthday Hangover', start: new Date(1355097600*1000), end: new Date(1355097600*1000), allDay: false, url: 'http://www.yahoo.com'},{ id: 3, title: 'Sepotomus Maximus Christmas', start: new Date(1356393600*1000), end: new Date(1356393600*1000), allDay: false, url: 'http://www.yahoo.com/'},]
Everything works just fine. What can I do to fix this problem? I though that using events: output would place the text in that location but it does not seem to be working.
Thank you all kindly in advance for any comments or answers!
Since you haven't given us much information, i'm going to take a shot in the dark and say that the browser is interpreting the json as text. So add a dataType property to the ajax call so that jQuery can parse the return as json.
$.ajax({
url: 'getevents.php',
data: { ufirstname: 'ufirstname' },
type: 'post',
dataType: 'json'
......
If you are getting that string in your alertbox.. You need to use JSON.parse() to parse the string into a javascript Object
change
events: output
to
events: JSON.parse(output)
According to the documentation
An "event source" is anything that provides FullCalendar with data about events. It can be a simple array, an event-generating function that you define, a URL to a json feed, or a Google Calendar feed.
Since version 1.5, Event Objects can have "options" associated with them. However, before you can start specifying options, you must write an Event Object in its extended form. It must be a traditional JavaScript object with properties.
Also your json string has an extra comma at the end
$year = date('Y');
$month = date('m');
echo json_encode(array(
array(
'id' => 111,
'title' => "Event1",
'start' => "$year-$month-10",
'url' => "http://yahoo.com/"
),
array(
'id' => 222,
'title' => "Event2",
'start' => "$year-$month-20",
'end' => "$year-$month-22",
'url' => "http://yahoo.com/"
)
));
The program actually wants this very specific format of json_encode or it does not work. I only figured this out by reading through all of these replies.
For getting selected row in grid, I use this:
'#deleteWorkerButton': {
click: function(me, e, eOpts){
var grid = Ext.ComponentQuery.query('Worker')[0];
var selected = grid.getSelectionModel().getSelection()[0];
grid.getStore().remove(selected);
}
}
In my store, I have url for posting this JSON but when I use json_decode I get this:
object(stdClass) {
id => "5";
name => "tets";
email => "era#sdfsa.com";
phone => "test";
}
But I need array(), not stdClass.
This is my store:
Ext.define('Sabrina.store.Workers', {
extend: 'Ext.data.Store',
fields:['id', 'name', 'email', 'phone'],
proxy: {
type: 'ajax',
api: {
create : 'php/usuarios.php?action=insert',
read : '../mega_sabrina_cake/workers/index',
update : 'php/usuarios.php?action=update',
destroy : '../mega_sabrina_cake/workers/delete'
},
actionMethods: {
create : 'POST',
read : 'POST',
update : 'POST',
destroy : 'POST'
},
reader: {
type: 'json',
root: 'Worker',
rootProperty: 'Worker',
successProperty: 'success',
messageProperty: 'message'
},
writer: {
type: 'json',
writeAllFields: true,
root: 'data',
encode: true
},
},
autoLoad: true,
autoSync: true
});
So, I'm using this for DELETING data. What can I do with my store to get a "NORMAL" array when json_decode()?
I think the problem is in:
grid.getStore().remove(selected);
Just read the docs:
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
[...]
assoc
When TRUE, returned objects will be converted into associative arrays.
Try adding allowSingle: false to writer configuration. By default it is set to true, which means single record changes sended without array wrap.