ExtJS 5.1, grid load data from database with PHP - php

I am doing an online course of Ext JS 5.1 and in this exercise I have a service.php file which connects to database and returns JSON Data. I try to show this data but it never gets displayed (doesn't show any error message in firebug) and I can`t find what is the problem with the code.
This is the code of the store:
var storeUsuario = Ext.create('Ext.data.Store', {
model : 'js.clase.Usuario',
proxy: {
type: 'rest',
url: 'service.php?method=getUsuarios',
reader: {
type: 'json',
}
},
autoLoad: true
});
This is the code of the grid:
Ext.create('Ext.grid.Panel', {
renderTo: Ext.getBody(),
store: storeUsuario,
width: 600,
height: 400,
title: 'Grid Usuarios',
columns: [
     {
text: 'id',
dataIndex: 'id'
},{
            text: 'nombre',
            width: 100,
            dataIndex: 'nombre'          
},{
        text: 'apellidos',
        dataIndex: 'apellidos'
},{
        text: 'email',
        dataIndex: 'email'
},{
        text: 'nacionalidad',
        dataIndex: 'nacionalidad'
},{
        text: 'rutaAvatar',
        dataIndex: 'rutaAvatar'
}
]
});
and the service.php method:
<?php
header('Content-Type: text/html; charset=utf-8');
$conexion = mysql_connect("127.0.0.1", "root", "");
mysql_select_db("usertest", $conexion);
$method = $_GET['method'];
switch($method) {
case "getUsuarios":
$query = "SELECT * FROM Usuario ORDER BY id ASC";
$result = mysql_query($query, $conexion) or die(mysql_error());
$numRows = mysql_num_rows($result);
$usuarios = array();
if ($numRows > 0) {
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$usuarios[$i] = $row;
$i++;
}
}
$usuariosJSON = json_encode($usuarios);
echo $usuariosJSON;
break;
}
?>

Your PHP code doesn't return a valid JSon.
See this fiddle works correctly: https://fiddle.sencha.com/#fiddle/q9k

According to this post you should specify the header.
And I suggest you to return a "hand formed" json like this:
$data = /** whatever you're serializing **/;
$data_length = /* the length of the result according to the request response */;
header('Cache-Control: no-cache, must-revalidate'); // just to be sure
header('Content-Type: application/json');
echo "{ \"success\": true, \"total\": $data_length, \"records\": " . json_encode($data) . " }";
The json data could need []...
echo "{ \"success\": true, \"total\": $data_length, \"records\": [ " . json_encode($data) . " ] }";

Related

Load data from database to set highchart X-axis with php json data

new to this and (almost) desperate. in below code i want to set $rows1['date'][] = $data['tanggal']; data as X-Axis in highchart :
$(function () {
var chart;
$(document).ready(function() {
getAjaxData(1);
var val = location.search.split('proyek=')[1]
getAjaxData(val);
function getAjaxData(proyek){
$.getJSON("src/json/data.php", {proyek: proyek}, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve-proyek',
type: 'column'
},
title: {
text: ''
},
credits: {
enabled: false,
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
title: {
text: ''
},
},
xAxis: {
type: 'datetime',
labels: {
formatter: function ( ){
return Highcharts.dateFormat('%Y-%m-%d', this.value);
},
},
},
tooltip:{
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.numberFormat(this.y, 2) +' %';
},
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'+'%',
}
},
},
series: json
});
});
};
});
});
my data.php :
<?php
header("Content-type: application/json");
require_once "database.php";
$db = new database();
$mysqli = $db->connect();
$proyek = $_GET['proyek'];
$sql = "SELECT fren_pr FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows = array();
$rows['name'] = 'Rencana';
$rows['color'] = '#50B432';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows['data'][] = array($data['fren_pr'],);
}
$sql = "SELECT freal_pr, tanggal FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows1 = array();
$rows1['name'] = 'Realisasi';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows1['data'][] = $data['freal_pr'];
$rows1['date'][] = $data['tanggal'];
}
$rslt = array();
array_push($rslt, $rows);
array_push($rslt, $rows1);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$mysqli->close();
this is my json view :
I've spent a lot of time trying to solve it but haven't found a solution until now.
Is there an error in my php code?
hope someone will be kind enough to help, Thanks in advance.

PHP with DataTables gives an Invalid JSON response due to quotes

I encountered a problem fetching my data from my database and display it via DataTables. I found out that most of my data has single and double quotes and other special characters. I tried every escaping functions in PHP but it didn't work. addslashes only retrieves 59 data out of 40,000 data. So far, i have this code:
PHP:
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$table = '';
while($row = mysqli_fetch_array($query)) {
$table.= '{
"allotment_code":"'.$row['allotment_code'].'",
"activity":"'.$row['activity'].'",
"category_name":"'.addslashes($row['category_name']).'",
"description":"'.addslashes($row['description']).'"
},';
}
$table = substr($table,0, strlen($table) - 1);
echo '{"data":['.$table.']}';
**jQuery data tables:**
$(function() {
$('#dataTables-example').DataTable( {
"bLengthChange": false,
"pageLength": 50,
"bDeferRender": true,
"bProcessing": true,
"sPaginationType": "full_numbers",
"ajax": base_url('ajax/ajaxGetBOM.php'),
"columns":[
{mData: "allotment_code"},
{mData: "activity"},
{mData: "category_name"},
{mData: "description"}
],
contentType: 'application/json',
dataType: 'json'
});
})
function base_url(path) {
var url = 'https://192.168.3.254/'+path;
return url;
}
The error is like this:
Use json_encode() function to properly encode your response using JSON format.
$query = mysqli_query($new_conn, "SELECT * FROM bill_of_materials");
$data = array();
while($row = mysqli_fetch_array($query)) {
$data[] = array(
"allotment_code" => $row["allotment_code"],
"activity" => $row["activity"],
"category_name" => $row["category_name"],
"description" => $row["description"]
);
}
header("Content-type: application/json");
echo json_encode(array("data" => $data));

Issue using dependsOn on jTable

I want to create a cascade dropdown on jTable using PHP on the server side. I've been following the demo provided in the API, but despite my efforts I don't seem to get it working. Using firebug I found out the AJAX request to fill the second dropdown is not being made. Anyway, here's part of the code I have. Hope you can throw some light on this.
The first dropdown is called "Region" and the second one "Trabajo", depending on the Region I want to pull from the database the workplaces that belong to it.
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'Colaboradores',
paging: true,
sorting: true,
defaultSorting: 'no_empleado ASC',
actions: {
listAction: 'usuariosActions.php?action=list',
createAction: 'PersonActionsPagedSorted.php?action=create',
updateAction: 'PersonActionsPagedSorted.php?action=update'
},
fields: {
no_empleado: {
title: 'Numero de colaborador',
key: true,
edit: false,
},
nombres: {
title: 'Nombres',
},
apellido_paterno: {
title: 'Apellido paterno',
},
apellido_materno: {
title: 'Apellido materno',
},
genero: {
title: 'Genero',
type: 'radiobutton',
options:{'0':'FEMENINO','1':'MASCULINO'},
list:false
},
fecha_nacimiento: {
title: 'Fecha de nacimiento',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
estado_civil: {
title: 'Estado civil',
options:{ '-1':'','1': 'CASADO', '2': 'DIVORCIADO', '3': 'SOLTERO','4':'UNION LIBRE','5':'VIUDO' },
list:false
},
dependientes: {
title: 'Número de dependientes',
options:{ '-1':'','0':'0','1': '1', '2': '2', '3': '3','4':'4','5':'5','6':'6','7':'7','8':'8','9':'9','10':'10','11':'11','12':'12','13':'13','14':'14','15':'15','16':'16','17':'17','18':'18','19':'19','20':'20' },
list:false
},
seguro_social: {
title: 'Número de seguridad social',
list:false
},
RFC: {
title: 'RFC',
list:false
},
calle: {
title: 'Calle',
list:false
},
no_ext: {
title: 'No. Ext',
list:false
},
no_int: {
title: 'No. Int',
list:false
},
colonia: {
title: 'Colonia',
list:false
},
mun_del: {
title: 'Del/Mun',
list:false
},
zip: {
title: 'Zip',
list:false
},
telefono: {
title: 'Telefono',
list:false
},
entidad_federativa: {
title: 'Entidad federativa',
list:false
},
fecha_antiguedad: {
title: 'Fecha ingreso',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
fecha_puesto: {
title: 'Fecha de inicio en el puesto',
type: 'date',
displayFormat: 'yy-mm-dd',
list:false
},
escolaridad: {
title: 'Escolaridad',
options:{ '-1':'','1': 'PRIMARIA', '2': 'SECUNDARIA', '3': 'PREPARATORIA','4':'UNIVERSIDAD','5':'ESPECIALIDAD','6':'POSGRADO','7':'MAESTRIA' },
list:false
},
puesto: {
title: 'Puesto',
list:false
},
contrato: {
title: 'Contrato',
options: {'-1':'','1':'Contrato por Tiempo Indeterminado','2':'Contrato por Tiempo Determinado','3':'Contrato por Obra Determinada','4':'Contrato por Tiempo Determinado'},
list:false
},
ocupacion:{
title: 'Ocupacion',
type: 'textarea',
list:false
},
region: {
title: 'Región',
options: 'usuariosActions.php?action=region',
list:false
},
trabajo: {
title: 'Centro de trabajo',
dependsOn: 'region',
options: function(data){
if(data.source == 'list'){
return 'usuariosActions.php?action=workplaces&region=0';
}
return 'usuariosActions.php?action=workplaces&region=' + data.dependedValues.region;
},
list:false
}
}
});
$('#LoadRecordsButton').click(function (e) {
e.preventDefault();
$('#PeopleTableContainer').jtable('load', {
no_empleado: $('#no_empleado').val()
});
});
//Load person list from server
$('#LoadRecordsButton').click();
});
</script>
And here's the PHP code
<?php
require_once("dbconnect.php");
if($_GET["action"] == "list")
{
//Get record count
if(isset($_POST['no_empleado']) && $_POST['no_empleado'] != ""){
$sql_result = 'SELECT
c.`no_empleado`,
c.`nombres`,
c.`apellido_paterno`,
c.`apellido_materno`,
c.`fecha_nacimiento`,
c.`fecha_antiguedad`,
c.`fecha_puesto`,
c.`estado_civil`,
c.`dependientes`,
c.`seguro_social`,
C.`escolaridad`,
C.`puesto`,
C.`RFC`,
C.`genero`,
C.`contrato`,
C.`ocupacion`,
C.`calle`,
C.`no_int`,
C.`no_ext`,
C.`colonia`,
C.`zip`,
C.`mun_del`,
C.`telefono`,
C.`entidad_federativa`,
c.`id_workplace` as trabajo,
r.`id_region` as region
FROM `colaboradores` AS c
INNER JOIN `workplaces` AS w
ON w.`id_workplace` = c.`id_workplace`
INNER JOIN `regiones` AS r
ON r.`id_region` = w.`id_region`
WHERE `no_empleado`= '.$_POST["no_empleado"].';';
$sql_count = 'SELECT COUNT(*) AS RecordCount FROM `colaboradores` WHERE `no_empleado`= '.$_POST["no_empleado"].';';
}
else{
$sql_result = 'SELECT
c.`no_empleado`,
c.`nombres`,
c.`apellido_paterno`,
c.`apellido_materno`,
c.`fecha_nacimiento`,
c.`fecha_antiguedad`,
c.`fecha_puesto`,
c.`estado_civil`,
c.`dependientes`,
c.`seguro_social`,
C.`escolaridad`,
C.`puesto`,
C.`RFC`,
C.`genero`,
C.`contrato`,
C.`ocupacion`,
C.`calle`,
C.`no_int`,
C.`no_ext`,
C.`colonia`,
C.`zip`,
C.`mun_del`,
C.`telefono`,
C.`entidad_federativa`,
r.`id_region` as region,
c.`id_workplace` as trabajo
FROM `colaboradores` AS c
INNER JOIN `workplaces` AS w
ON w.`id_workplace` = c.`id_workplace`
INNER JOIN `regiones` AS r
ON r.`id_region` = w.`id_region`
ORDER BY ' . $_GET["jtSorting"] . ' LIMIT ' . $_GET["jtStartIndex"] . ',' . $_GET["jtPageSize"] . ';';
$sql_count = 'SELECT COUNT(*) AS RecordCount FROM `colaboradores`';
}
$result = $mysqli->query($sql_count);
$row = $result->fetch_assoc();
$recordCount = $row['RecordCount'];
//Get records from database
$result = $mysqli->query($sql_result);
//Add all records to an array
$rows = array();
while($row = $result->fetch_assoc())
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
}
if($_GET["action"] == "region"){
$sql_count = 'SELECT `id_region` as Value ,`nombre_region` as DisplayText FROM `regiones`;';
$result = $mysqli->query($sql_count);
$rows = array();
while($row = $result->fetch_assoc()){
$rows[] = $row;
}
//Get records from database
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult);
}
if($_GET["action"] == "workplaces"){
$region=$_GET['region'];
if ($region == "")
$result = $mysqli->query("SELECT `id_workplace` as Value, `nombre_workplace` as DisplayText FROM `workplaces` ");
else
$result = $mysqli->query("SELECT `id_workplace` as Value, `nombre_workplace` as DisplayText FROM `workplaces` WHERE `id_region` = '".$region."'");
$rows = array();
while ($row = $result->fetch_assoc()) {
$rows[] = $row;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult);
}
I was right, dependsOn was not sending any sort of event signal and therefore the ajax call wasn't being made. I was using the min.js that came with the zip but it wasn't the newest version, 2.4.0, it was 2.2.0. it seems this functionality was not implemented yet on that version or was buggy.
Anyway, stick to version 2.4.0 and make sure to take a look into the js version if you run into trouble.

how to create proper json data format from mysql for highcharts

I have a json data that will retrive the selected data from database based on user checked on checkboxes. but I know my json data is not correct. Tried many way, but still wont works. This is the code:
<?php
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series1['name'][] = $r['subject'];
$series1['data'][] = $r['result'];
}
$jsonTable = json_encode($series1, JSON_NUMERIC_CHECK);
echo $jsonTable;
}
Based from the code below, lets say if I checked 3 checkbox (BAT123, BIO222, HIS TEST),The json output will be like this:
{"name":["BAT123"],"data":[3.03]}
{"name":["BAT123","BIO222"],"data":[3.03,1.05]}
{"name":["BAT123","BIO222","his test"],"data":[3.03,1.05,3.03]}
I know the json above was wrong, So how to make the json data will be display like this:
[
{"name":["BAT123"],"data":[3.03]},
{"name":["BIO222"],"data":[1.05]},
{"name":["his test"],"data":[3.03]}
]
This is my highcharts javascript code:
<script type="text/javascript">
$(function () {
var data = [
<?php echo $jsonTable; ?>
];
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'SamHistogramDiv',
type: 'column',
marginRight: 130,
marginBottom: 25
},
title: {
text: 'SAM Histogram Results',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
categories: []
},
yAxis: {
title: {
text: 'Percentage'
},
plotLines: [{
value: 0,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 100,
borderWidth: 0
},
series: data[0]
});
});
});
Thank u very much for your time..
Problem was with the json data format. It should be like
var data = [{name:"BAT123",data:[3.03]},{name:"BIO222",data:[1.05]},{name:"his test",data:[3.03]}];
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>array($r['result']));
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
Pls check if you are getting the json string as mentioned above /* data */
Check this link
http://jsfiddle.net/highcharts/Sq3KL/2/
Try this
foreach ($_GET['iddoc'] as $iddoc) //iddoc is the value of checked checkbox
{
$query="select * from compareresult where iddocument=$iddoc";
$sql_query = mysql_query($query) or die('Error 3 :'.mysql_error());
while ($r = mysql_fetch_assoc($sql_query))
{
$series[] = array('name'=>$r['subject'],'data'=>$r['result']);
}
}
$jsonTable = json_encode($series);
echo $jsonTable;
the out put will be like
[{"name":"BAT123","data":"3.03"},{"name":"BIO222","data":"1.05"},{"name":"HIs test","data":"1.00"}]

Ext Tree, Data is displayed in console, but does not display on page

My data is displayed in console, but does not display in ExtJs tree?
My php file
$data = array();
$sql = "";
if (!isset($_POST['node'])) {
// first select the top node that have no parent
$sql = "SELECT id_no,value_data FROM extjs_tree WHERE parent IS NULL";
} else {
// select data with parent_id = $_POST['node']
$sql = "SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $_POST['node'] ."'";
}
$q = mysql_query($sql);
while ($r = mysql_fetch_array($q)) {
// check if have a child node
$qq = mysql_query("SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $r['id'] ."'");
if (mysql_num_rows($qq) > 0) {
// if have a child
$r['leaf'] = false;
$r['cls'] = 'folder';
} else {
// if have no child
$r['leaf'] = true;
$r['cls'] = 'file';
}
$data[] = $r;
}
echo json_encode($data);
My JS file
Ext.require([
'Ext.tree.*',
'Ext.data.*',
'Ext.tip.*'
]);
Ext.onReady(function() {
Ext.QuickTips.init();
var store = Ext.create('Ext.data.TreeStore', {
proxy: {
type:'ajax',
actionMethods:'post',
url:'get-nodes.php'
},
root: {
text: 'Root Node',
id: 'root_node',
expanded: true
},
folderSort: true,
sorters: [{
property:'text',
direction:'ASC'
}]
});
var tree = Ext.create('Ext.tree.Panel', {
store: store,
renderTo: 'tree_el',
height: 300,
width: 250,
title: 'Products Display'
});
});
I am getting the tree properly, I can see the data in the console. But I cannot see ExtJs displaying the values??
My present result
My expected result should be
In your case you can also add following field to your store:
{
name: 'text',
mapping: 'value'
}
Every item of response has to have text field in it. As I can see from your request-response images You don't send text field. Response should be looking like the following one:
[{
"id": 2,
"text": "Fruits", // this field is required
...
},
...
]

Categories