Extjs Don't load Grid. PHP - php

Somebody would helpme with this code:Grid dont load infomations.
Below is the code I'm using, but the grid carries no information.
Extjs
Ext.onReady(function(){
var store = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
proxy: {
type: 'ajax',
url: 'data.php',
reader: {
type: 'json',
root: 'country',
idProperty: 'total'
}
},
//alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
fields: ['name', 'area']
});
Ext.create('Ext.grid.Panel', {
title: 'Retorno',
//store: Ext.data.StoreManager.lookup('simpsonsStore'),
store:store,
columns: [
{ text: 'Name', dataIndex: 'name' },
{ text: 'Area', dataIndex: 'area', flex: 1 }
],
height: 200,
width: 400,
renderTo: Ext.getBody()
});
});
data.php here is the code with json code.
<?php
print '{
"total": 10,
"country": [
{
"name": "CULTIV",
"area": "6.96120082466223e-007"
},
{
"name": "asdASdasd",
"area": "123123123"
}
]
}';
?>

I think you need to set the store's autoLoad configuration to true. If you do not set this attribute, then you will need to call the load() method of the store.
Option 1
var store = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
autoLoad:true,
proxy: {
type: 'ajax',
url: 'data.php',
reader: {
type: 'json',
root: 'country'
//idProperty: 'total'
}
},
//alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
fields: ['name', 'area']
});
Option 2
var store = new Ext.data.JsonStore({
// store configs
storeId: 'myStore',
proxy: {
type: 'ajax',
url: 'data.php',
reader: {
type: 'json',
root: 'country'
//idProperty: 'total'
}
},
//alternatively, a Ext.data.Model name can be given (see Ext.data.Store for an example)
fields: ['name', 'area']
});
store.load();
I created a working fiddle for a demonstration.

Related

how to combine to array for chartjs width php

i need help how to make php code for array data to chartjs, i use 2 table and i hope to generate array code like below
function revenueCost(year) {
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name=\'csrf-token\']').attr('content')
},
url: url,
data: {
year: $('#year').val(),
},
type: 'POST',
dataType: 'JSON',
success:function(data){
// console.log(data);
$('#revenue-cost').empty();
var myChart = new Chart(document.getElementById('revenue-cost'), {
type: 'bar',
data: {
labels: data.label,
datasets: [{
label: 'Revenue',
data: data.revenue,
borderWidth: 0.5,
borderColor: '#00642c',
backgroundColor: 'rgba(0,100,44,0.2)'
},{
label: 'Cost',
data: data.cost,
borderWidth: 0.5,
borderColor: '#a80e19',
backgroundColor: 'rgba(168,14,25,0.2)'
}]
},
options: {
scales: {
yAxes: [{
ticks: {beginAtZero: true}
}]
}
}
});
},
});
}
and i want to make array like this
{"label":["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],"revenue":[105,85,55,68,72,8,0,0,0,0,0,0],"cost":[41,32,22,23,26,3,0,0,0,0,0,0]}
and chartjs view like this
chartjs grouping month
As I see the solution could be simple:
Send a POST HTTP request to your PHP file.
Validate you have a POST request with an if sentence and isset($_POST)
Prepare or extract the data, and create an associative array like the next one:
$label_data = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
$revenue_data = [105,85,55,68,72,8,0,0,0,0,0,0];
$cost_data = [41,32,22,23,26,3,0,0,0,0,0,0];
$data = [
'label' => $label_data,
'revenue' => $revenue_data,
'cost' => $cost_data
];
echo json_encode($data);
if you have data divided between arrays just merge them with array_merge and store the result in a new variable
$label_first = ["Jan","Feb","Mar","Apr","May","Jun"];
$label_second = ["Jul","Aug","Sep","Oct","Nov","Dec"];
$label_data = array_merge($label_first, $label_second );
Finally catch the response in your $.ajax and, perform the action you want to do the data.
I hope this information could be useful for you.

ChartJS and Ajax calls

I would like to make charts using ChartJS and PHP ( Silex Framework )
This is my ajax call
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output;
},
error: function () {
alert("Oops there is an error.");
}});
This is my PHP function which i managed to call
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
return ?????
}
And here is my chart :
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
Route.php
$app->post('/stats', function () use ($app) {
session_start();
if(isset($_POST['method']) && !empty($_POST['method'])) {
$method = $_POST['method'];
switch($method) {
case 'dossierRepartitionType' :
$dossiers=$app['dao.dossier']->dossierRepartitionType();
break;
}
}
return new ResponseSilex("$dossiers");
});
So my AJAX call the route and then get the result of the function into $dossiers which is ouput in the Reponse, am i doing it right ?
How can i return an array with all the datas value for each count ?
I struggle to catch error and to find a proper way to bind MYSQL count value to my chart
Thank you
The main idea is that you should format your data in your model, then return JSON to the front end via json_encode. After that, you would parse the json in your ajax returns and then pass the appropriate data to the chart.
it's very easy, you need to modify your php code like this:
public function dossier(){
$stmt = "SELECT count(*) as total FROM dossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$number_of_rows = $rows->fetchColumn();
return json_encode(["total" => $number_of_rows]);
In your ajax petition you are specifying a "json" return so in your script php need's return a json.
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
dataDossierRepartitionType=output.total;
},
error: function () {
alert("Oops there is an error.");
}});
You should to receive a json from php with this structure
{total: rows_total}
so in your ajax response you'll receive that answer and you can get the data like this:
dataDossierRepartitionType=output.total;
Sorry for my english, hope can help you
You can send JSON data from php
Try this:
Php:
public function dossier(){
$stmt = "SELECT count(*) FROM dossier GROUP BY typedossier";
$stmt = $this->db->prepare($stmt);
$rows=$stmt->execute();
$rows = $stmt->fetch(PDO::FETCH_NUM);
exit(json_encode(array('counts' => $rows)));
}
After ajax successfully complete you need to initialize chart plugin inside success callback like below:
Ajax:
$.ajax({ url: 'stats',
data: {method: 'dossierRepartitionType'},
type: 'post',
datatype: 'json',
success: function(output) {
if (output.counts) {
dataDossierRepartitionType=output.counts.join();
alert(dataDossierRepartitionType)
initCharts(dataDossierRepartitionType);
}
},
error: function () {
alert("Oops there is an error.");
}});
Finally wrap chart initialization code inside callback function
Chart:
function initCharts(dataDossierRepartitionType){
var ctx = document.getElementById("myChart");
ctx.width = 400;
ctx.height = 400;
data = {
datasets: [{
data: [dataDossierRepartitionType, 20],
backgroundColor: [
'rgb(255, 99, 132)',
'rgb(54, 162, 235)',
],
borderColor: [
'white',
'white',
],
borderWidth: 1
}],
// These labels appear in the legend and in the tooltips when hovering different arcs
labels: [
'Red',
'Blue',
]
};
var myDoughnutChart = new Chart(ctx, {
type: 'doughnut',
data: data,
options: {
legend: {
labels: {
fontColor: "white",
fontSize: 18
}
},
maintainAspectRatio: false,
responsive: false
}
});
}

Query String Filtering with Datatables in Laravel 5.4

im using YajraBox for Datatables, it is Laravel extension.
I want to make it work with my Query String Filtering, so idea is tah i need to pass search request to ajax request
This is part of my form imput:
http://127.0.0.1:8000/lots?make%5B%5D=TOYOTA
So result have to be: only lots made by TOYOTA
This is my script for datatables with YajraBox:
<script type="text/javascript">
$(document).ready(function(){
$('#table').DataTable({
bInfo: false,
searching: false,
processing: true,
serverSide: true,
ajax: '{{ url("/data") }}',
columns: [
{ data: 'date', name: 'date' },
{ data: 'bid', name: 'bid' },
{ data: 'auction_name', name: 'auction_name' },
{ data: 'pics_urls', name: 'pics_urls' },
{ data: 'company', name: 'company' },
{ data: 'model_name_en', name: 'model_name_en' },
{ data: 'model_type_en', name: 'model_type_en' },
{ data: 'grade_en', name: 'grade_en' },
{ data: 'mileage_en', name: 'mileage_en' },
{ data: 'model_year_en', name: 'model_year_en' },
{ data: 'color_en', name: 'color_en' },
{ data: 'displacement', name: 'displacement' },
{ data: 'transmission_en', name: 'transmission_en' },
{ data: 'scores_en', name: 'scores_en' },
{ data: 'start_price_en', name: 'start_price_en' },
{ data: 'result_en', name: 'result_en' }
]
});
});
</script>
This is my controllers for view and for ajax:
public function index()
{
return view('lots.browse');
}
public function indexData(LotFilters $filters)
{
$lots = Lot::filter($filters);
return Datatables::eloquent($lots)->make(true);
}
So what i think, i need to pass some howe ?make%5B%5D=TOYOTA to ajax request ajax: '{{ url("/data") }}',, any one know how to do it?
You can do this like:
"{{ url('/data') }}" + "?make="+value // where value contains TOYOTA in it
and get this value in controller like:
Input::get('make');

Extract text from input extjs and send it to php

I have a login with username and password, and a button with login. I want to send data from username and password to server-side PHP.
Ext.require([
'Ext.form.Panel',
'Ext.layout.container.Anchor'
]);
var log = Ext.onReady(function () {
Ext.create('Ext.form.Panel', {
renderTo: 'login',
title: 'Login section',
bodyPadding: '10 10 0',
width: 300,
fieldDefaults: {
labelAlign: 'top',
msgTarget: 'side'
},
defaults: {
border: false,
xtype: 'panel',
flex: 1,
layout: 'anchor'
},
layout: 'hbox',
items: [{
items: [{
xtype: 'textfield',
fieldLabel: 'User Name',
anchor: '-5',
name: 'first',
id: 'userName'
}, {
xtype: 'textfield',
fieldLabel: 'Password',
anchor: '-5',
name: 'password',
inputType: 'password',
id: 'password'
}]
}
],
buttons: ['->', {
text: 'Login',
name: 'submit',
/*listeners: {
tap: function () {
var form = Ext.getCmp('userName');
//var values = form.getValues();
Ext.Ajax.request({
url: 'index.php',
params: form,
success: function (response) {
var text = response.responseText;
Ext.Msg.alert('asfasfaf', text);
},
failure: function (response) {
Ext.Msg.alert('Error', 'Error while submitting the form');
console.log(response.responseText);
}
});
}
}*/
/* handler: function () {
Ext.Ajax.request({
url: 'index.php',
method: 'POST',
params: Ext.getCmp('userName').getValue(),
success: function (response) {
Ext.Msg.alert('success ' + Ext.getCmp('userName').getValue());
},
failure: function (response) {
Ext.Msg.alert('server-side failure with status code ' + response.status);
}
});
}*/
},
{
text: 'Register?'
}]
});
});
I see that you have already tried to extract values and send request to php. May be this structure will help you. But you have to be sure that your php url accepts parameters with names 'param1' and 'param2' (or whatever your php accepts:) )
{
xtype : 'button',
text : "Submit"
formBind : true,
handler : function() {
var userName = this.up('form').down('#userName');
var password = this.up('form').down('#password');
Ext.Ajax.request({
url: url, // your php url
method: 'POST',
params: {param1: userName, param2:password },
disableCaching: false,
success: function(response, opts)
{
var text = response.responseText; // for debugging print text and decodedText
var decodedText = Ext.decode(text);
if(decodedText.success)
{
}
}
failure: function()
{
}
});
}
}
Ext.getCmp('userName').getValue();
You can use the Ext Form's submit method from within your button handler, e.g.:
// ....
buttons: [{
text: 'Submit!',
handler: function(btn) {
btn.up('form').getForm().submit({
url: 'mybackend.php',
success: function(ret) {},
failure: function(ret) {},
});
}
}],
// .....

Extjs 4 store sync issue

I have the following code:
The Store :
Ext.define('strClientesRECO', {
extend: 'Ext.data.Store',
model: 'mdlClientesRECO',
autoLoad: false,
proxy: {
type: 'ajax',
pageParam: undefined,
startParam: undefined,
limitParam: undefined,
api: {
read: 'some url',
create: 'some url',
update: 'some url',
},
reader: {
type: 'json',
root: 'data',
successProperty: 'success',
messageProperty: 'message'
},
writer: {
root: 'records',
encode: true,
writeAllFields: false
}
}
});
The grid has the following properties:
selModel: Ext.create('Ext.selection.CheckboxModel'),
selType: 'cellmodel',
plugins: [{
ptype: 'cellediting',
clicksToEdit: 2
}],
In the controller I have a listener to sync the store every cell update
Ext.ComponentQuery.query('viewGridClientesRECO')[0].getStore().addListener('update', this.onUpdateRecords, this);
onUpdateRecords: function() {
var storeGridClientes = Ext.ComponentQuery.query('viewGridClientesRECO')[0].getStore();
storeGridClientes.sync();
},
But in the PHP file that is executed when I update, if I print $_POST the records sends are correct, but it never sends the id of the edited row.

Categories