Why is the select display showing the value instead of the label? - javascript

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) );
}
}
?>

Related

Protect a page from external access outside the server

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.

Saving cart details in a database using simplecart.js

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.

datatables button change/filter content based on variable sent

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
});

JavaScript - Sending a post request to a PHP element

var table = $('#accessRequest').DataTable({
"dom": 'Blfrtip',
"ajax": "Editor-PHP-1.5.1/php/editor-serverside.php",
"columns": [
{ //special column for detail view
"className": 'details-control',
"orderable": false,
"data": null,
"defaultContent": ''
},
{ data: "DT_RowId",
render: function ( data ) {
return data.replace( 'row_', '' );
}
},
{ data: null,
render: function ( data, type, row ) {
// Combine the first and last names into a single table field
return data.first+' '+data.last;
}
},
{ "data": "phone" },
{ "data": "responsibleParty" },
{ "data": "email" },
{ "data": "building" },
{ "data": "typeOfWork" },
{ "data": "startTime" },
{ "data": "endTime" },
{ "data": "description" },
{ "data": "dockNeeded" },
{ "data": "numPeople" },
{ "data": "numTrucks" },
{ "data": "requestPlaced" },
{ "data": "updatedAt" },
{ "data": "approved" },
{ "data": "approvedBy" },
{ "data": "approvedAt" },
{ "data": null }
],
"aoColumnDefs": [
{
"aTargets": [-1],
"mData": null,
"mRender": function (data, type, full) {
return '<button id="ApprovalButton" onclick="$.post(\'extra.php\', \'approve_request\')" action="extra.php" method="post"> Process </button>';
//Send post request
}
}
],
"order": [[1, 'asc']],
select: true,
buttons: [
{ extend: "create", editor: editor },
{ extend: "edit", editor: editor },
{ extend: "remove", editor: editor }
]
});
I have a string of code (above) in which I am creating a table to contain information. On the line that says "//send post request" I'm trying to make it so the button directly above it sends a post request to a separate file called "extra.php", and despite what I've done I haven't been able to that.
I've tried using a submit button in an input form, but that didn't work. I've tried a lot of different things, but I can't seem to get it to work. Any help would be appreciated.
There is already a file (extra.php) that is capable of receiving a post request and acting on it once it has received it. I'm attempting to create a button in HTML on a page, that when clicked posts 'approve_request' to the file "extra.php"
Sorry, I'm new to both coding and this website, there's probably something simple that I'm not doing.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
header('Access-Control-Allow-Origin: *');
$id = intval($_POST['id']);
$con = mysql_connect("RequestAccess.db.10160035.hostedresource.com","RequestAccess","br#6HeCher");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("RequestAccess", $con);
//if action sent is approve set request as apporved
if(isset($_POST['approve_request'])){
$sql = "UPDATE AccessRequests
SET approved='1', approvedAt=current_timestamp
WHERE AccessID='" . $_POST['approve_request']."'";
$results = mysql_query($sql);
}
//else action sent must be for child rows so populate child row
else {
}
This is the section responsible for handling the post request, if that helps.
I think you are missing this:
"processing": true,
"serverSide": true,
DataTabele needs these directives to know that you want perform the request to the php script.
And maybe also this:
"ajax": "your php.php"
Remove your database credentials from this post immediately.
Your backend script shouldn't have any HTML associated with it. You can't return headers if you've already output to the DOM.
Documentation: http://php.net/manual/en/function.header.php
For data-tables you will need to return json from the backend script. It should look something like this. Assuming your SQL and Schema is correct.
<?php
//Use PDO this is deprecated.
$con = mysql_connect("stuff","things","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("RequestAccess", $con);
$id = (int) $_POST['id'];
if(isset($_POST['approve_request'])){
$sql = "
UPDATE AccessRequests
SET approved='1', approvedAt=current_timestamp -- this may need to be in quotes.
WHERE AccessID='{$_POST['approve_request']}'
";
$results = mysql_query($sql);
} else {
$results = null;
}
//Set headers
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
//Output data.
echo json_encode($results);
I use a program to debug my ajax requests. Firebug is a good option.
I would highly suggest learning a framework first (guard rails are nice).
http://www.sitepoint.com/best-php-framework-2015-sitepoint-survey-results/

Paging not working, Extjs grid

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);

Categories

Resources