I made an extjs grid with a bottom toolbar to create a paging behavior, but it's not working and I don't know where is the problem, I've already done it with local data, but when i used a database it didn't work, it shows all the data at once.
Here's the code :
Ext.require([ 'Ext.data.*', 'Ext.grid.*' ]);
Ext.onReady(function() {
var categoriesStore = Ext.create('Ext.data.JsonStore', {
autoLoad: true,
pageSize : 10,
proxy: {
type: 'ajax',
url: 'GridDataBase/categories.php',
reader: {
type: 'json',
totalProperty: 'total',
root: 'categories',
idProperty: 'name'
}
},
fields : ['id','name']
});
var panelOfData = Ext.create('Ext.grid.GridPanel',{
store : categoriesStore,
columns : [ {
id : 'id',
header : "Id",
width : 20,
sortable : true,
dataIndex : 'id'
}, {
id : 'name',
header : "Category Name",
width : 75,
sortable : true,
dataIndex : 'name'
} ],
//stripeRows : true,
//paging bar on the bottom
bbar: Ext.create('Ext.PagingToolbar', {
store: categoriesStore,
displayInfo: true,
displayMsg: '{0} - {1} of {2}',
emptyMsg: "No categories to display"
}),
autoExpandColumn : 'name',
height : 350,
width : 600,
renderTo : 'grid-ex',
title : 'Categories'
});
categoriesStore.loadPage(1);
console.log(categoriesStore.count()); // the log here shows 0
});
Here's the PHP file :
function GetCategories() {
$query = "SELECT id, name FROM categorie";
$categories = array("categories" => array());
#mysql_connect("localhost","superuser","SS4") or die();
mysql_select_db("dbz"); !mysql_error () or die();
$result = mysql_query($query);
$num = mysql_num_rows($result);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$categories["categories"][$i] = $row;
$i++;
}
return json_encode($categories);
}
echo GetCategories();
Extjs code sends some additional params for implementing the paging on server start, limit and these params have to be used in your query to send back records upto the pagesize limit of store. Server response should also send back a property with total number of records (to be assigned to totalProperty of store) which will be used to calculate number of pages.
store.load({
params:{
start:0,
limit: itemsPerPage
}
});
Hope it helps!!
You havent implemented paging on server side. Try this:
function GetCategories($start, $limit) {
$query = "SELECT id, name FROM categorie LIMIT $start, $limit";
$categories = array("categories" => array());
#mysql_connect("localhost","superuser","SS4") or die();
mysql_select_db("dbz"); !mysql_error () or die();
$result = mysql_query($query);
$num = mysql_num_rows($result);
$i = 0;
while ($row = mysql_fetch_assoc($result)) {
$categories["categories"][$i] = $row;
$i++;
}
return json_encode($categories);
}
$start = isset($_GET['start']) ? $_GET['start'] : 0;
$limit = isset($_GET['limit']) ? $_GET['limit'] : 0;
echo GetCategories($start, $limit);
Related
In a backend panel, in order to populate a datatable, I echo the records in a php page in format JSON, then I parse, format and populate the datatable with JS.
The issue is, how do I prevent peoples from accessing that php page and leaking all the informations?
This is what my code look like:
var options = {
data: {
type: 'remote',
source: {
read: {
url: 'http://127.0.0.1/inc/phpscripts/printinfo.php',
},
},
pageSize: 10,
serverPaging: false,
serverFiltering: false,
serverSorting: false,
},
layout: {
scroll: false,
footer: false
},
sortable: true,
pagination: true,
columns: [{
field: 'id',
title: '#',
sortable: false,
width: 20,
selector: {
class: ''
},
textAlign: 'center',
}, {
field: 'name',
title: 'name',
}, {
field: 'surname',
title: 'surname',
}, {
field: 'address',
title: 'address',
}, {
field: 'phone',
title: 'phone',
},
}],
};
This is the code of the printinfo.php
function datatable($userid){
global $conn;
$total = totalrows($userid);
$pagination = ceil($total/10);
echo '{
"meta": {
"page": 1,
"pages": '.$pagination.',
"perpage": 10,
"total": '.$total.',
"sort": "desc",
"field": "name"
},
"data":';
$rows = array();
$query = $conn->prepare('SELECT * FROM table WHERE id = ? ORDER BY name DESC');
$query->bind_param('i', $userid);
if (!$query->execute());
$res = $query->get_result();
$counter = 0;
//$rows = array();
while ($data = $res->fetch_assoc()) {
$rows[] = $data;
}
print json_encode($rows);
echo '}';
}
datatable(SESSION['id']);
While this is the display content of printinfo.php
{ "meta": { "page": 1, "pages": 1, "perpage": 10, "total": 4, "sort": "desc", "field": "level" }, "data":
[{"id":1,"name":"frank","surname":"blank","address":"st andrew","phone":"+1555484845"},
{"id":1,"name":"andrew","surname":"blank","address":"st paroli","phone":"+1555895685"}]}
It works fine, but I don't think this is secure at all.
So, how would you approach it in order to secure the datas?
You should build some authentication scheme, in order to validate the identity of user that fetches your data.
A simple example (not secure at all, but shows the goal) - send some identification code as post request to that php script and validate it there.
Better security can be achieved by creating a database with hashed or encrypted passwords and validating the user at sign in stage. After that validation, you can store some credentials on the server and check in your php script the identity.
Again, this is not so simple as described and should be done carefully.
I am using simplecart.js. The cart displays properly. What I want to do now is to retrieve the details in the cart and insert into a database.
Here is my code.
simpleCart({
cartColumns: [
{ attr: "name", label: "Name" },
{ attr: "price", label: "Price", view: 'currency' },
{ view: "decrement", label: false },
{ attr: "quantity", label: "Qty" },
{ view: "increment", label: false },
{ attr: "total", label: "SubTotal", view: 'currency' },
{ view: "remove", text: "Remove", label: false }
],
cartStyle: "table",
checkout: {
type: "SendForm",
url: base_url + "Checkout/checkout_function",
method: "POST",
success: base_url + "/Checkout/success",
cancel: base_url + "Checkout/cancel"
}
});
simpleCart.bind('beforeCheckout', function (data) {
data.full_name = document.getElementById("full_name").value;
data.phone = document.getElementById("phone").value;
data.country = document.getElementById("country").value;
data.state = document.getElementById("state").value;
data.city = document.getElementById("city").value;
data.address1 = document.getElementById("address1").value;
data.address2 = document.getElementById("address2").value;
data.zip = document.getElementById("zip").value;
data.address_type = document.getElementById("address_type").value;
});
And the PHP file
for($i=1; $i < $content['itemCount'] + 1; $i++)
{
$prod_name = 'item_name_'.$i; /* product name variable */
$quantity = 'item_quantity_'.$i; /* product quantity variable */
$price = 'item_price_'.$i; /* product price variable */
$shipping = 'simpleCart_shipping_'.$i; /* Shipping cost */
$total = $content[$quantity]*$content[$price]; /* product total price variable (price*quantity) */
$grandTotal += $total; /* accumulating the total of all items */
}
The issue is when I try to echo any of the variables,does not display the content from the cart. Please how do I get the variables to contain the actual content, inserting them into a database will not be a problem.
I'm using datatables with the buttons plugin. I have two buttons that filter the content that is displayed based on a variable that I need to send to the server, so the ajax url has to change everytime I click one button.
$('#example').DataTable( {
processing: true,
lengthChange: false,
dom: 'Bfrtip',
ajax: {
url: '/get?op=10',
dataSrc: ''
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'surname' },
{ data: 'phone' },
{ data: 'email' },
{ data: 'nin' }
],
buttons: [
{
text: 'Everyone',
// action ??
},
{
text: 'Owners',
},
{
text: 'Applicants',
}
],
select: true
});
The third button should reset the ajax url to the original one.
public function get_address_book_table($id, $owner = 0) {
$mysqli = $this->aet->getAetSql();
$mysqli->set_charset('utf8');
switch ($owner) {
case 0: $a = $b = NULL; break;
case 1: $a = 'pd.applicant_id'; $b = 'INNER JOIN property_demand pd ON pd.applicant_id = ab.id'; break;
case 2: $a = 'po.owner_id'; $b = 'INNER JOIN property_owner po ON po.owner_id = ab.id'; break;
}
$query = 'SELECT ab.*, sab.*' . $a . '
FROM address_book ab
INNER JOIN staff_address_book sab ON sab.contact_id = ab.id' .
$b . '
WHERE sab.staff_id = ?';
if ($stmt = $mysqli->prepare($query)) {
$stmt->bind_param('s', $id);
$stmt->execute();
$stmt->bind_result($id, $name, $surname, $phone, $email, $nin, $note, $a, $b);
$data = [];
while ($stmt->fetch()) {
$nestedData = [];
$nestedData['id'] = $id;
$nestedData['name'] = $name;
$nestedData['surname'] = $surname;
$nestedData['phone'] = $phone;
$nestedData['email'] = $email;
$nestedData['nin'] = $nin;
$data[] = $nestedData;
}
}
return $data;
}
And the get file:
// address_book table
if ($op === 10) {
$owner = isset( $_GET['owner'] ) ? (int) $_GET['owner'] : 0;
$result = $functions->get_address_book_table($staff->getId(), $owner);
header('Content-type: text/json');
header('Content-type: application/json');
echo json_encode($result);
}
I'm looking for an option for the button plugin that allow me to change the ajax url on click so that the table is refreshed with the new server content.
You need to set a value in the button event, and pass that value as a parameter to the server. Finally, you probably want to trigger the ajax data reload when you click the button. Try something like this:
var filterType = 'all';
$('#example').DataTable( {
processing: true,
lengthChange: false,
dom: 'Bfrtip',
serverSide: true,
ajax: {
url: '/get',
//dataSrc: 'data',
data: function(d) {
d.op = 10;
d.filterType = filterType;
}
},
columns: [
{ data: 'id' },
{ data: 'name' },
{ data: 'surname' },
{ data: 'phone' },
{ data: 'email' },
{ data: 'nin' }
],
buttons: [
{
text: 'Everyone',
action: function(e, dt) { filterType = 'all'; dt.ajax.reload(); }
},
{
text: 'Owners',
action: function(e, dt) { filterType = 'owner'; dt.ajax.reload(); }
},
{
text: 'Applicants',
action: function(e, dt) { filterType = 'app'; dt.ajax.reload(); }
}
],
select: true
});
I'm trying to use a select with inline editing. I have gotten this to display properly using the popup for editing, but I want it all to be inline and submit on blur. My data includes both an ID and a name for each dropdown item, which I have in an object that looks like { label: "blah", value: "blah" } etc.
However, in the DataTable the dropdowns are all being displayed with the ID instead of the label as the default value. I don't want users to see the id. I tried setting the editor field name to be the label and the DataTable column to be the value, which seemed to work for the popup but for inline editing I get the error "Uncaught Unable to automatically determine field from source. Please specify the field name".
My initializations look like this:
editor = new $.fn.dataTable.Editor({
ajax: 'url',
table: '#table',
idSrc: 'id',
fields: [{
label: "Location",
name: "location_name", //this is where the problem is, I think
type: "select",
ipOpts: locationList
}]})
$('#table').dataTable({
dom: "Tfrtip",
"searching": false,
"ajax": {
"url": "url",
"type": "GET"
},
"columnDefs": [
{ "visible": false, "targets": [8] }
],
"columns": [
{ "data": "location_id" }
])}
If I change the DataTable to use the name, the display is correct, but I get the name submitted to the database instead of the ID, and I need the ID.
What should I do?
I did it like this, it's messy but works:
Each editable object has it's own span class. An ID that relates to the parent object. A key that relates to the object that is being updated. And then of course the data.
<td><span class="dcmeta" data-value="'.$row['DATACENTER'].'" data-type="select" id="'.$row['CLUSTERNAME'].'" key="DATACENTER">'.$row['DATACENTER'].'</span></td>
<td><span class="tiermeta" data-value="'.$row['TIER'].'" data-type="select" id="'.$row['CLUSTERNAME'].'" key="TIER">'.$row['TIER'].'</span></td>
Javascript:
<script type="text/javascript">
jQuery(document).ready(function() {
$.fn.editable.defaults.mode = 'popup';
$('.xedit').editable();
$('.tiermeta').editable({
title: 'Test title',
source: [
{value: 'Tier 1', text: 'Tier 1'},
{value: 'Tier 2', text: 'Tier 2'},
]
});
$('.dcmeta').editable({
title: 'Test title',
source: [
{value: 'DC1', text: 'DC1'},
{value: 'DC2', text: 'DC2'},
]
});
$(document).on('click','.editable-submit',function(){
var key = $(this).closest('.editable-container').prev().attr('key');
var x = $(this).closest('.editable-container').prev().attr('id');
var y = $('.input-metadata').val();
var z = $(this).closest('.editable-container').prev().text(y);
$.ajax({
url: "process.php?id="+x+"&data="+y+"&key="+key,
type: 'GET',
success: function(s){
if(s == 'status'){
$(z).html(y);}
if(s == 'error') {
alert('Error Processing your Request! ');}
},
error: function(e){
alert('Error Processing your Request!! ');
}
});
});
});
</script>
PHP:
<?php
$conn = sqlsrv_connect( $serverName, $connectionInfo );
if( $conn === false ) {
die( print_r( sqlsrv_errors(), true));
}
if($_GET['id'] and $_GET['data'] and $_GET['key'])
{
$id = $_GET['id'];
$data = $_GET['data'];
$key = $_GET['key'];
$sql = "update CLUSTER set $key='$data' where CLUSTERNAME='$id'";
echo 'success';
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
}
?>
Hi i have extjs grid in Column Model currently my grid is appearing normally with rows now i want to display
my gird rows in icon view. . so what can i do for that ?
also can we take button in tbar with type Xtemplate so by passing array to Xtemplate Constructor we can overwrite Xtemplate in grid., if it so then how to do that ?
will you please tell me ?
datastore = new Ext.data.Store({ // data store
...
proxy: new Ext.data.HttpProxy({
..
}),
reader: new Ext.data.JsonReader({
...
])),
}),
var gridtb = new Ext.Toolbar([ // Tool bar
{
xtype: "tbbutton",
id: 'tb_home',
icon: '<?php echo _EXT_URL ?>/images/_home.png',
text: '<?php echo ext_Lang::msg('homelink', true ) ?>',
tooltip: '<?php echo ext_Lang::msg('homelink', true ) ?>',
cls:'x-btn-text-icon',
handler: function() { chDir('') }
},
...
var cm = new Ext.grid.ColumnModel({ // Colum model..
columns: [
{
...
css: 'white-space:normal;'
}
...
})
var viewport = new Ext.Viewport({ //Viewport to display grid. . in centre region . .
layout:'border',
..
items: [
{
xtype: "editorgrid",
region: "center",
title: "<?php echo ext_lang::msg("actdir", true ) ?>",
autoScroll:true,
collapsible: false,
closeOnTab: true,
id: "gridpanel",
ds: datastore,
cm: cm,
tbar: gridtb,
bbar: gridbb,
...
}
})