How can I fill a grid from MySQL and PHP? ExtJS 4 - javascript

I know this question has been published before (a bunch of times actually) but I'm asking it because I have absolutely no idea what I can be doing wrong.
What I'm trying to do is just that, filling (or binding) a grid with data that I've got stored in my MySQL database.
This is what I've got so far:
Ext.define('UserDataModel', {
extend: 'Ext.data.Model',
fields: ['name', 'age']
});
var usersStore = Ext.create('Ext.data.Store', {
model: 'UserDataModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'dbhandler/acquisition.php',
reader: {
type: 'json',
successProperty: 'success',
root: 'usersData'
}
}
});
var gridPanel = Ext.create('Ext.grid.Panel', {
store: usersStore,
columns: [{
dataIndex: 'name',
header: 'Name',
flex: 1
}, {
dataIndex: 'age',
header: 'Age',
flex: 1
}]
});
And this is my PHP file:
<?php
include('../connections/usersdb.php');
$query = "SELECT Name, Age FROM Users";
$result = $conn->query($query);
$usersData = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push($usersData, array("name" => $row['Name'], "age" => $row['Age']))
}
}
$conn->close();
echo json_encode(array("success" => true, "usersData" => $usersData)); ?>
But the grid isn't getting filled.
And what drives even crazier is that the console doesn't throw me any error.

Related

How do i use a variable in the columns section of an ajax request for data tables

I'm trying to add dynamic values for the column section in an ajax request so that the users can have control over what fields are in the data tables.
I tried with default values and it worked but when i changed to use dynamic values from a variable, the ajax field gives me errors
this works fine;
$(function() {
$('#myTable').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('members.create') }}',
columns: [
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'address', name: 'address' },
{ data: 'contact', name: 'contact' },
{ data: 'nationality', name: 'nationality' },
{ data: 'dob', name: 'dob' },
{ data: 'hometown', name: 'hometown' },
{ data: 'action', name: 'action', orderable: false, searchable: false }
]
});
});
this is where the problem comes in;
$(function() {
$('#myTable').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('members.create') }}',
columns: [
var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
for(var i = 0; i < memberFields.length; i++){
{ data: memberFields[i], name: memberFields[i] };
},
{ data: 'action', name: 'action', orderable: false, searchable: false }
]
});
});
Thats because column property wants an array .
And your structure to build array is incorrect .
Do this :
$(function() {
var memberFields = <?php echo json_encode($chosen_member_fields, JSON_UNESCAPED_UNICODE); ?>;
var columnArray = [];//To save for value into an Array
for(var i = 0; i < memberFields.length; i++){
columnArray.push({ data: memberFields[i], name: memberFields[i] });//push valuse to array
},
columnArray.push({ data: 'action', name: 'action', orderable: false, searchable: false });//push last value
$('#myTable').DataTable({
processing: true,
serverSide: true,
ajax: '{{ route('members.create') }}',
columns: columnArray , //just say Array name !
});
});
Didnt test but hope works

JSON response empty when return Ajax Call

I am following a tutorial using Ext JS 4. I would like for a user to be able to login the application after being authenticated. I have already created the user name and password in the database.
The problem is my JSON response is coming back empty when I click my submit button.
I have an AJAX call in my Login.js controller that calls my login.php which establishes my database connection.
Login.js
Ext.define('Packt.controller.Login', {
extend: 'Ext.app.Controller',
requires: [
'Packt.util.MD5',
'Packt.util.Alert',
'Packt.view.MyViewport',
'Packt.util.Util',
'Packt.util.SessionMonitor'
],
views: [
'Login',
'Header',
'authentication.CapsLockTooltip'
],
refs: [
{
ref: 'capslockTooltip',
selector: 'capslocktooltip'
}
],
init: function(application) {
this.control({
"login form button#submit": {
click: this.onButtonClickSubmit
},
"login form button#cancel": {
click: this.onButtonClickCancel
},
"login form textfield": {
specialkey: this.onTextfielSpecialKey
},
"login form textfield[name=password]": {
keypress: this.onTextfielKeyPress
},
"appheader button#logout": {
click: this.onButtonClickLogout
}
});
Ext.apply(Ext.form.field.VTypes, {
// vtype validation function
customPass: function(val, field) {
return /^((?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%]).{6,20})/.test(val);
},
// vtype Text property: The error text to display when the validation function returns false
customPassText: 'Not a valid password. Length must be at least 6 characters and maximum of 20Password must contain one digit, one letter lowercase, one letter uppercase, onse special symbol ##$% and between 6 and 20 characters.'
});
},
onButtonClickSubmit: function(button, e, options) {
var formPanel = button.up('form'),
login = button.up('login'),
user = formPanel.down('textfield[name=user]').getValue(),
pass = formPanel.down('textfield[name=password]').getValue();
if (formPanel.getForm().isValid()) {
pass = Packt.util.MD5.encode(pass);
Ext.get(login.getEl()).mask("Authenticating... Please wait...", 'loading');
Ext.Ajax.request({
url: 'php/login.php',
params: {
user: user,
password: pass
},
success: function(conn, response, options, eOpts) {
Ext.get(login.getEl()).unmask();
var result = Packt.util.Util.decodeJSON(conn.responseText);
if (result.success) {
//Packt.util.Alert.msg('Success!', 'User Authenticated.');
login.close();
Ext.create('Packt.view.MyViewport');
Packt.util.SessionMonitor.start();
} else {
Packt.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
Ext.get(login.getEl()).unmask();
Packt.util.Util.showErrorMsg(conn.responseText);
}
});
}
},
onButtonClickCancel: function(button, e, options) {
button.up('form').getForm().reset();
},
onTextfielSpecialKey: function(field, e, options) {
if (e.getKey() == e.ENTER){
var submitBtn = field.up('form').down('button#submit');
submitBtn.fireEvent('click', submitBtn, e, options);
}
},
onTextfielKeyPress: function(field, e, options) {
var charCode = e.getCharCode();
if((e.shiftKey && charCode >= 97 && charCode <= 122) ||
(!e.shiftKey && charCode >= 65 && charCode <= 90)){
if(this.getCapslockTooltip() === undefined){
Ext.widget('capslocktooltip');
}
this.getCapslockTooltip().show();
} else {
if(this.getCapslockTooltip() !== undefined){
this.getCapslockTooltip().hide();
}
}
},
onButtonClickLogout: function(button, e, options) {
Ext.Ajax.request({
url: 'php/logout.php',
success: function(conn, response, options, eOpts){
var result = Packt.util.Util.decodeJSON(conn.responseText);
if (result.success) {
button.up('mainviewport').destroy();
window.location.reload();
} else {
Packt.util.Util.showErrorMsg(conn.responseText);
}
},
failure: function(conn, response, options, eOpts) {
Packt.util.Util.showErrorMsg(conn.responseText);
}
});
}
});
login.php
<?php
require("db/db.php");
session_start();
// username and password sent from form
$userName = $_POST['user'];
$pass = $_POST['password'];
// To protect MySQL injection (more detail about MySQL injection)
$userName = stripslashes($userName);
$pass = stripslashes($pass);
$userName = $mysqli->real_escape_string($userName);
$pass = $mysqli->real_escape_string($pass);
$sql = "SELECT * FROM USER WHERE userName='$userName' and password='$pass'";
$result = array();
if ($resultdb = $mysqli->query($sql)) {
// determine number of rows result set
$count = $resultdb->num_rows;
// If result matched $userName and $pass, table row must be 1 row
if($count==1){
$_SESSION['authenticated'] = "yes";
$_SESSION['username'] = $userName;
$result['success'] = true;
$result['msg'] = 'User authenticated!';
} else {
$result['success'] = false;
$result['msg'] = 'Incorrect user or password.';
}
/* close result set */
$resultdb->close();
}
/* close connection */
$mysqli->close();
//JSON encoding
echo json_encode($result);
?>
db.php
<?php
//$server = "192.168.0.11";
$server = "127.0.0.1";
$user ="mark";
$pass = "dog";
$dbName = "sakila";
$mysqli = new mysqli($server, $user, $pass, $dbName);
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
?>
I have also created a Login.js view page to display the pop up panel for user to login in.
Login.js view
Ext.define('Packt.view.Login', {
extend: 'Ext.window.Window',
alias: 'widget.login',
requires: [
'Packt.view.Translation'
],
autoShow: true,
height: 170,
width: 360,
layout: {
type: 'fit'
},
iconCls: 'key',
title: translations.login,
closeAction: 'hide',
closable: false,
items: [
{
xtype: 'form',
frame: false,
bodyPadding: 15,
defaults: {
xtype: 'textfield',
anchor: '100%',
labelWidth: 60,
allowBlank: false,
vtype: 'alphanum',
minLength: 3,
msgTarget: 'under'
},
items: [
{
name: 'user',
fieldLabel: translations.user,
maxLength: 25,
value: 'mark'
},
{
inputType: 'password',
name: 'password',
fieldLabel: translations.password,
enableKeyEvents: true,
id: 'password',
maxLength: 15,
value: '123456',
//vtype: 'customPass',
msgTarget: 'side'
}
],
dockedItems: [
{
xtype: 'toolbar',
dock: 'bottom',
items: [
{
xtype: 'translation'
},
{
xtype: 'tbfill'
},
{
xtype: 'button',
itemId: 'cancel',
iconCls: 'cancel',
text: translations.cancel
},
{
xtype: 'button',
itemId: 'submit',
formBind: true,
iconCls: 'key-go',
text: translations.submit
}
]
}
]
}
]
});
I am not sure how to debug this. I seems like it is making the database connection. but i not returning anything back. How can I authenticate this pre existing user and login?

EXT JS JsOnStore can't show in Grid Panel

vehicle.js
Ext.Loader.setConfig({enabled: true});
Ext.Loader.setPath('Ext.ux', 'ux/');
Ext.require([
'Ext.tip.QuickTipManager',
'Ext.tree.*',
'Ext.data.*',
'Ext.window.MessageBox',
'Ext.window.*',
]);
Ext.onReady(function() {
Ext.QuickTips.init(); //tips box
Ext.define('MyApp.view.MyGridPanel', {
extend: 'Ext.grid.Panel',
renderTo: Ext.getBody(),
width: window.innerWidth,
header: false,
height: window.innerHeight,
store: UserStore,
initComponent: function() {
var me = this;
Ext.applyIf(me, {
columns: [
{
xtype: 'gridcolumn',
dataIndex: '_id',
text: 'Vehicle ID'
},
{
xtype: 'numbercolumn',
width: 126,
dataIndex: 'Plat_No',
text: 'Plat Number'
}
],
dockedItems: [
{
xtype: 'toolbar',
dock: 'top',
items: [
{
xtype: 'button',
cls: '',
width: 59,
icon: '',
iconCls: 'save',
text: 'Save'
},
{
xtype: 'button',
cls: '',
width: 59,
icon: '',
iconCls: 'edit',
text: 'Edit'
}
]
}
]
});
me.callParent(arguments);
}
});
var win = Ext.create('MyApp.view.MyGridPanel');
win.show();
Ext.define('VehicleModel', {
extend: 'Ext.data.Model',
fields: ['_id', 'Plat_No']
});
Ext.override(Ext.data.Connection, {
timeout : 840000
});
var UserStore = Ext.create('Ext.data.JsonStore', {
model: 'VehicleModel',
autoLoad: false,
proxy: {
type: 'ajax',
url: 'get-vehicle.php',
baseParams: { //here you can define params you want to be sent on each request from this store
//groupid: 'value1',
},
reader: {
type: 'json'
}
}
});
UserStore.load({
params: { //here you can define params on 'per request' basis
//groupid: 1,
}
})
}); // on ready
get-vehicle.php
<?php
mysql_connect("localhost", "root", "123456") or die("Could not connect");
mysql_select_db("db_shuttlebus") or die("Could not select database");
$parent_id = $_GET['groupid'];
$query = "SELECT * FROM tbl_vehicle";
$rs = mysql_query($query);
$arr = array();
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo json_encode($arr);
?>
but the grid panel still is blank, but the firebug return the get-vehicle.php like below
/localhost/BusTicket/vehicle/get-vehicle.php?_dc=1386449682081&page=1&start=0&limit=25
ParamsHeadersResponseHTML
[{"_id":"1","Plat_No":"PKN7711"},{"_id":"2","Plat_No":"AKC1234"},{"_id":"3","Plat_No":"ADB4333"}]
what is the problem?
In your proxy reader definition you have defined root to "images"
Because of this configuration reader expect JSON in this format:
{
'images': [
{"_id":"1","Plat_No":"PKN7711"},
{"_id":"2","Plat_No":"AKC1234"},
{"_id":"3","Plat_No":"ADB4333"}
]
}
If you remove root definition from your reader configuration, reader should process your current JSON format.
Problem Solved,
because UserStore need to be loaded before the grid panel load.
so, just modify the UserStore in front of grid panel. done

extjs 4: list view select image id and display the image on other panel

Ext.require([
'Ext.grid.*',
'Ext.data.*',
'Ext.panel.*'
]);
Ext.onReady(function(){
Ext.define('ImageModel', {
extend: 'Ext.data.Model',
fields: ['name', 'url', {name:'size', type: 'float'}, {name:'lastmod', type:'date', dateFormat:'timestamp'}]
});
var store = Ext.create('Ext.data.JsonStore', {
model: 'ImageModel',
proxy: {
type: 'ajax',
url: 'get-images.php',
reader: {
type: 'json',
root: 'images'
}
}
});
store.load();
var listView = Ext.create('Ext.grid.Panel', {
width:425,
height:250,
collapsible:true,
title:'Simple ListView <i>(0 items selected)</i>',
renderTo: Ext.getBody(),
store: store,
multiSelect: true,
viewConfig: {
emptyText: 'No images to display'
},
columns: [{
text: 'File',
flex: 50,
dataIndex: 'name'
},{
text: 'Last Modified',
xtype: 'datecolumn',
format: 'm-d h:i a',
flex: 35,
dataIndex: 'lastmod'
},{
text: 'Size',
dataIndex: 'size',
tpl: '{size:fileSize}',
align: 'right',
flex: 15,
cls: 'listview-filesize'
}]
});
// little bit of feedback
listView.on('selectionchange', function(view, nodes){
var l = nodes.length;
var s = l != 1 ? 's' : '';
listView.setTitle('Simple ListView <i>('+l+' item'+s+' selected)</i>');
});
});
i have create 2 panel, one is left panel,second is right panel.
the list view are created in the left panel,and the right panel will read the page showimage.php
list view are display file detail,when user select the list view will passing the file name as a parameter "name" to showimage.php, and the right panel will show the image by name are passed from list view select event.(actually the name field are stored file's ID)
Question
1)how to create the select list view event,when select a list view passing parameter name to showimage.php,and right panel refresh the page and display the image.
//===========================LIST VIEW===============================
Ext.define('ImageModel', {
extend: 'Ext.data.Model',
fields: ['PicID', 'PicUploadedDateTime','PicData']
});
var ImgStore = Ext.create('Ext.data.JsonStore', {
model: 'ImageModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'get-image.php',
baseParams: { //here you can define params you want to be sent on each request from this store
mainid: 'value1',
startdate: 'value2',
enddate: 'value3'
},
reader: {
type: 'json',
root: 'images'
}
}
});
var listView = Ext.create('Ext.grid.Panel', {
region: 'west',
id : 'imagelist',
title: 'Select Image',
width: 200,
split: true,
collapsible: true,
floatable: false,
title:'Select Image',
store: ImgStore,
multiSelect: false,
viewConfig: {
emptyText: 'No images to display'
},
columns: [
{
text: 'Date Time Uploaded',
//xtype: 'datecolumn',
//format: 'Y-m-d H:i:s',
flex: 65,
width: 100,
dataIndex: 'PicUploadedDateTime'
}]
});
function hexToBase64(str) {
return btoa(String.fromCharCode.apply(null, str.replace(/\r|\n/g, "").replace(/([\da-fA-F]{2}) ?/g, "0x$1 ").replace(/ +$/, "").split(" ")));
}
listView.on('selectionchange', function(view, nodes){
/*
var nodeIdDisplay = "";
for(var i = 0; i < nodes.length; i++)
{
if(nodeIdDisplay.length > 0)
nodeIdDisplay += ",";
nodeIdDisplay += nodes[i].get("PicID");
}
*/
if (nodes[0].get("PicID") > 0){
//alert(nodes[0].get("PicData"));
image=Ext.getCmp('displayimage');
image.setSrc("data:image/jpeg;base64,"+hexToBase64(nodes[0].get("PicData")));
//console.log(nodes[0].get("PicData"));
}
});
this code method is post to the get-image.php,and get all the image in store and then,
list view on select change event get the image id and display the image on type : 'image' component

labelAlign: 'right' not working in my extjs form

I have a form panel and i want text fields stick to their labels but labelAlign:'right' isn't working and text fields are aligned centrally
here is my code:
Ext.ns('Tunkv.forms');
Tunkv.forms.user_settings = Ext.extend(Ext.form.FormPanel, {
// i inserted labelAlign here,maybe the wrong place???
labelAlign : 'right',
labelWidth : 80,
layout:'form'
,border:false
,frame:true
,url:'index.php?option=com_Tunkv&c=doctor&task=saveProfile&format=raw'
,constructor:function(config) {
config = config || {};
config.listeners = config.listeners || {};
Ext.applyIf(config.listeners, {
actioncomplete:function() {
if(console && console.log) {
console.log('actioncomplete:', arguments);
}
}
,actionfailed:function() {
if(console && console.log) {
console.log('actionfailed:', arguments);
}
}
});
Tunkv.forms.user_settings .superclass.constructor.call(this, config);
}
,initComponent:function() {
var timezones = new Ext.data.SimpleStore({
fields: ['id', 'timezone'],
data : [<?php
echo $this->zonesdata;
?>]
});
var joomlaEditors = new Ext.data.SimpleStore({
fields: ['id', 'editor'],
data : [<?php
echo $this->editors;
?>]
});
var languages = new Ext.data.SimpleStore({
fields: ['id', 'language'],
data : [<?php
echo $this->languages;
?>]
});
var ext_templates = new Ext.data.SimpleStore({
fields: ['id', 'ext_template'],
data : [<?php
echo $this->ext_template;
?>]
});
// hard coded - cannot be changed from outside
var config = {
items: [{
xtype: 'textfield',
fieldLabel: 'Name',
name: 'name',
allowBlank: false,
value: '<?php
echo $user->name;
?>',
maxLength: 32,
maxLengthText: 'Maximum name length is 36 characters.',
msgTarget:'side'
},{
xtype: 'textfield',
fieldLabel: 'Username',
name: 'username',
minLength: 2, maxLength: 32,
minLengthText:'Username must be at least 2 characters long. ',
maxLengthText: 'Maximum username length is 36 characters.',
value: '<?php
echo $user->username;
?>',
allowBlank : false,
msgTarget:'under'
},{
xtype: 'textfield',
inputType: 'password',
fieldLabel: 'Password',
name: 'password',
minLength: 6,
maxLength: 32,
minLengthText: 'Password must be at least 6 characters long.',
maxLengthText: 'Maximum Password length is 36 characters.',
msgTarget:'under'
},{
xtype: 'textfield',
fieldLabel: 'Email',
name: 'email',
vtype: 'email',
allowBlank : false,
value: '<?php
echo $user->email;
?>',
msgTarget:'under'
},{
xtype: 'combo',
name: 'joomlaeditor',
fieldLabel: 'Editor',
mode: 'local',
store: joomlaEditors,
displayField:'editor',
value: '<?php
echo $user->getParam ( 'editor' );
?>',
msgTarget:'under'
},{
xtype: 'combo',
name: 'language',
fieldLabel: 'Language',
mode: 'local',
store: languages,
displayField:'language',
value: '<?php
echo $user->getParam ( 'language' );
?>',
msgTarget:'under'
},{
xtype: 'combo',
name: 'timezone',
fieldLabel: 'Timezone',
mode: 'local',
store: timezones,
displayField:'timezone',
value: '<?php
echo $user->getParam ( 'timezone' );
?>'
,
msgTarget:'under'
},{
xtype: 'combo',
name: 'ext_template',
fieldLabel: 'Skin',
mode: 'local',
store: ext_templates,
displayField:'ext_template',
value: '<?php
echo $user->getParam ( 'ext_template' );
?>'
,msgTarget:'under'
},{
xtype: 'hidden',
fieldLabel: '<?php
echo JUtility::getToken ();
?>',
name: '<?php
echo JUtility::getToken ();
?>',
value: '<?php
echo JUtility::getToken ();
?>',
hideLabel:true
}]
,buttons:[{
text:'Submit'
,formBind:true
,scope:this
,handler:this.submit
}]
}; // eo config object
// apply config
Ext.apply(this, Ext.apply(this.initialConfig, config));
// call parent
Tunkv.forms.user_settings .superclass.initComponent.apply(this, arguments);
} // eo function initComponent
/**
* Form onRender override
*/
,onRender:function() {
// call parent
Tunkv.forms.user_settings .superclass.onRender.apply(this, arguments);
// set wait message target
this.getForm().waitMsgTarget = this.getEl();
} // eo function onRender
/**
* Submits the form. Called after Submit buttons is clicked
* #private
*/
,submit:function() {
this.getForm().submit({
url:this.url
,scope:this
,success:this.onSuccess
,failure:this.onFailure
//,params:{cmd:'save'}
,waitMsg:'Saving...'
});
} // eo function submit
/**
* Success handler
* #param {Ext.form.BasicForm} form
* #param {Ext.form.Action} action
* #private
*/
,onSuccess:function(form, action) {
Ext.Msg.show({
title:'Success'
,msg:'Form submitted successfully'
,modal:true
,icon:Ext.Msg.INFO
,buttons:Ext.Msg.OK
});
} // eo function onSuccess
/**
* Failure handler
* #param {Ext.form.BasicForm} form
* #param {Ext.form.Action} action
* #private
*/
,onFailure:function(form, action) {
this.showError(action.result.error || action.response.responseText);
} // eo function onFailure
/**
* Shows Message Box with error
* #param {String} msg Message to show
* #param {String} title Optional. Title for message box (defaults to Error)
* #private
*/
,showError:function(msg, title) {
title = title || 'Error';
Ext.Msg.show({
title:title
,msg:msg
,modal:true
,icon:Ext.Msg.ERROR
,buttons:Ext.Msg.OK
});
} // eo function showError
}); // eo extend
// register xtype
Ext.reg('settingsform', Tunkv.forms.user_settings );
// invalid markers to sides
Ext.form.Field.prototype.msgTarget = 'side';
// create and show window
var userSettingsWindow = new Ext.Window({
title: 'Settings panel'
,layout:'fit'
,width:800
,height:520
,closable:true
,items:{id:'formloadsubmit-form', xtype:'settingsform'}
});
// eof
labelAlign : 'right'
Controls the position and alignment of the fieldLabel and should be inserted into fieldset config object and not inside forms config object.
For example:
{
xtype: 'combo',
name: 'ext_template',
fieldLabel: 'Skin',
mode: 'local',
store: ext_templates,
displayField:'ext_template',
value: 'value',
msgTarget:'under',
labelAlign : 'right'
}
If some one is looking for a way to "position" the label on the right of the field
(common for checkboxes) the property to use is:
boxLabel: 'Some text AFTER the field',
for the xtype "radio", label on the right doesn't work. You can check it out (latest code). What I found can be a work around is instead of using fieldLabel, use boxLabel instead for radio buttons. I hope they fix this annoying bug soon.

Categories

Resources