Strange JSON when deleting row in grid (Ext-JS 4) - php

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.

Related

Set background color attribute for single cell with Laravel DataTables

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:

Select2 ajax option using YII Framework

I am using Yii framework on a project and i am using an extension which uses select2 jquery. I am unable to grasp how the implementation for ajax works with this extension or the select2.
My ajax call returns the following json.
[
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"},
{"id":"1", "text" : "Option one"}
]
The yii extension enfolds the select2 extension as below
$this->widget('ext.select2.ESelect2', array(
'name' => 'selectInput',
'ajax' => array(
'url'=>Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'type' => 'GET',
'results' => 'js:function(data,page) {
var more = (page * 10) < data.total; return {results: data, more:more };
}',
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
),
));
I found a related question from this Question! The link to the extension am using is YII select2 Extention!
So a week later i merged with the answer to this question.
First let me highlight how the select2 ajax or in my case the Yii ESelect Extension.
The ajax options for jquery are the same as for the Eselect Extention i.e. url,type and datatype altho there is a slight difference on the format returned after successfully querying.
As for the result set for Eselect/select2 expects two parameters to be returned. that is
id : data.myOptionsValue;
text : data.myOptionText;
Reference :: https://select2.github.io/options.html#ajax
if we want to customize the format for the result set that is retured we can go a head and extend the plugin by using
'formatResult' => 'js:function(data){
return data.name;
}',
'formatSelection' => 'js: function(data) {
return data.name;
}',
I also had an issue getting my head around how the extention was quering. A look around and i realised that we have two datatype jsonp and json these two datatypes will handle data differently.
Jsonp (json padding) allows sending query parameters when querying. As for my case i am not passing any other parameters e.g an authkey e.t.c. In my case i changed the datatype to json and returning a json with id and text as results. See below my working snippet.
echo CHtml::textField('myElementName', '', array('class' => 'form-control col-lg-12'));
$this->widget('ext.select2.ESelect2', array(
'selector' => '#myElementName',
'options' => array(
'placeholder' => 'Search ..',
'ajax' => array(
'url' => Yii::app()->createUrl('controller/ajaxAction'),
'dataType' => 'json',
'delay' => 250,
'data' => 'js: function(term) {
return {
q: term,
};
}',
'results' => 'js: function(data){
return {results: data }
}',
),
),
));

Remove escape character from Jquery Post

To my issue there are several similar questions but I haven't found a good one that would help me solve my problem. My problem is:
I want to convert a JQuery object into a Json String, and then post this string to a PHP webPage, This is running very good. But when I received it on the server(php page) it is full of escape characters.
Here is my code on the client:
var jsonRemision = JSON.stringify(remision,false);
$.post("updateremision.php",
{
rem:jsonRemision,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: false,
},
function(data,status){
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
});
and here is the code on the server:
$remision = json_decode($_POST['rem']);
Now, when I see whats inside of $_POST['rem'] is full of escape characters \" . These escape character are not allowing me to jsondecode... The json full of escape characters looks like this:
{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}
How can I remove the escape characters ?? thanks in advance for any comment or help :)
I actually just recently had the same issue.
I fixed it by using stripslashes();
This should work ok unless you actually do have slashes in the data.
var_export(json_decode(stripslashes('{\"id\":\"12\",\"fecha\":\"2014-06-25\",\"ciudad\":\"Manizales\",\"camion\":\"NAQ376\",\"driver\":\"16075519\",\"cant\":\"0\",\"anticipos\":[{\"type\":\"1\",\"com\":\"Comment\",\"costo\":\"1234\"}]}'), true));
outputs:
array (
'id' => '12',
'fecha' => '2014-06-25',
'ciudad' => 'Manizales',
'camion' => 'NAQ376',
'driver' => '16075519',
'cant' => '0',
'anticipos' =>
array (
0 =>
array (
'type' => '1',
'com' => 'Comment',
'costo' => '1234',
),
),
)
You're calling $.post incorrectly. The second argument is all the POST parameters, it's not an options structure. If you want to pass options, you have to use $.ajax:
$.ajax("updateremission.php", {
data: { rem: jsonRemission },
dataType: "json",
success: function(data, status) {
if(status=="success"){
alert("Good Message");
}else{
alert("Bad Message");
}
}
});
You shouldn't use processData: false, because that will prevent the parameter from being put into $_POST['rem'].

flot piechart from PHP

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:

jQuery and array of objects

$(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.

Categories