highcharts $_post['value'] does not print chart values - javascript

I wanted to create a highchart using a dropdown and the selected value should be used in the where clause in a select statement. But if I click on the button then the chart is printed but with no values (e.g. dbsize, or timestamp...). If I change the $db variable to "postgres" or something like that, the chart will be printed normally.
Here is the html code:
<iframe name="hideframe" id="hideframe" style="display: none;"></iframe>
<form action="printchart.php" method="post" target="hideframe" >
<div class="dropdown" >
<select class="form-control" name="thenumbers" >
<option value="postgres">postgres</option>
<option value="template1">template1</option>
<option value="testdb">testdb</option>
</select>
</div>
<button name="Button5" id="Button5">click</button>
<div id="container" style="height: 400px; min-width: 310px">
<?php include("printchart.php"); ?>
</div>
And here is the printchart.php File including js for highchart:
<?php
require("00connection.php");
$db = $_POST['thenumbers'];
//$db = "postgres";
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$('#Button5').click(function () {
$(document).ready(function() {
var options ={
chart: {
renderTo: 'container',
type: 'line',
zoomType: 'x',
setSize: 400
},
title: {
text: "DB-Size"
},
xAxis: {
categories: [
<?php
$sql = $conn->query("SELECT dbname,dbsize, epoch_time FROM dbstats WHERE dbname = '$db' ORDER BY epoch_time;")->fetchAll();
foreach ($sql as $row) {
?> '<?php //echo (date('Y-m-d h:i:sa',$row['epoch_time']))
$date = $row['epoch_time'] / 1000;
echo (date('Y-m-d H:i', $date)) ?>',
<?php
}
?>
],
title: {
text: "Datetime"
},
type:'datetime',
labels: {
format: '{value:%Y-%m-%d %H:%M}',
}
},
yAxis: {
title: {
text: 'DB-Size'
}
},
rangeSelector: {
enabled: true,
inputEnabled: false,
buttonPosition: {
allign: 'left'
},
labelStyle: {
display: 'none'
},
buttons: [{
type: 'month',
count: 1,
text: '1m'
},
{
type: 'month',
count: 3,
text: '3m'
}
]
},
tooltip: {
//crosshairs: true,
shared: true,
valueSuffix: 'MB',
xDateFormat: '%Y-%m-%d %H:%M'
},
series: [{
name: 'DB-Size',
data: [
<?php
$sql = $conn->query("SELECT dbname, dbsize, epoch_time FROM dbstats WHERE dbname = '$db' ORDER BY epoch_time;")->fetchAll();
foreach ($sql as $row) {
?>
<?php echo $row['dbsize'] ?>,
<?php
}
?>
]
}]
};
var chart = new Highcharts.Chart(options);
});
});
</script>
The sql statements are executed normally in both cases (if i get the value using $_POST from the form or if I create a variable and initialize it with postgres (like $db="postgres") but if I assing $db=$_POST['thenumber'] then the chart will not be printed although the select statements are executed.
I hope anybody can help me :)
Here is the image:
highcharts_img
Best regards

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.

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

How can I load rows in JsGrid table that got from php file?

I tried to load rows of data from a table in MySQL. I used jsgrid with PHP.
My two php files connect to the localhost datanase and select rows from the tables using mysqli functions, and copy the result of the query into an array and send by json_encode() to an HTML file where I put the jsgrid code.
Then, I call the html file into other PHP file by <iframe> html tag.
The names of PHP files are:
newsConf, controll and getnewscat
HTML file: basic.html
in controll.php:
public function newsConfig(){
$this->CONN = new Conn();//class from external page to connect DB
try{
$dfnet = $this->CONN->open_connect();
$qnco = mysqli_query($dfnet,"select * from category");
if(!$qnco) return "";
else{
while($qncoarray = mysqli_fetch_row($qnco)){
//here I try copy rows into array
$nnopCo[] = array(
'ID' => $qncoarray['ID'],
'Name' => $qncoarray['Name']
);
}
return $nnopCo;
}
$this->CONN->close_connect($dfnet);
}
catch(Exception $er){
}
in getnewscat.php:
<?php require_once "../../bin/controll.php";
$db_controll = new Controll();
$cat_news = new ArrayObject($db_controll->newsConfig());
header('Content-type: application/json');
echo json_encode($cat_news->getArrayCopy());
?>
in basic.html: is the same file from jsgrid demo, but I change the code in javascript and canceled the db.js file
$(function() {
$("#jsGrid").jsGrid({
height: "70%",
width: "50%",//100%
selecting: false,
filtering: false,
editing: false,
sorting: false,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(clients){
var d = $.Deferred();
$.ajax({url: "../bin/getnewscat.php", dataType: "json",function(obj){
for (var i = 0; i < obj.length; i++) {
/*res[i]=data.i;
i++;*/
clients = {
"ID": obj.ID,
"Name": obj.Name
};
}
}
}).done(function(response) {
d.resolve(response.value);
});
return d.promise();
}
In newsConf.php: that file should call basic.html and give the result
by this:
<iframe name="demo" src="jsgrid-1.2.0/demos/basic.html"></iframe>
But the result is empty and I don't know why?, however I change the code but it didn't yield success.
What have I missed here?
Update
See my update below.
The done function should work. Remove success handler and put your mapping into done handler. Then put a debugger into done handler to ensure what you get in a response. Then map the response accordingly and resolve the deferred.
loadData: function(clients){
var d = $.Deferred();
$.ajax({
url: "../bin/getnewscat.php"
}).done(function(response) {
// put a debugger here to ensure that your response have 'value' field
var clients = $.map(response.value, function(item) {
return {
ID: item.SomeID,
Name: item.SomeName
};
});
d.resolve(clients);
});
return d.promise();
}
I'm not sure whether you need a mapping or not. Maybe you can remove it in the end. But do everything in the done handler and check the format of the response.
Sorry for my delay, but I think I got where's my mistake!
I fixed it and I got what I missed,
In controll.php file, I used mysqli_fetch_row() function, but I forgot I send the data in a named array, so I changed it to mysqli_fetch_assoc() function.
and about basic.html I changed it to:
<script>
$(function() {
{
$("#jsGrid").jsGrid({
height: "70%",
width: "50%",//100%
selecting: false,
filtering: false,
editing: false,
sorting: false,
paging: true,
autoload: true,
pageSize: 15,
pageButtonCount: 5,
controller: {
loadData: function(filter) {
//here how I fix it!
return $.ajax({url: "../bin/getnewscat.php",data:filter
});
}
},
////////////////////////////////////////////////////////////
fields: [
{ name: "ID", type: "number", width: 50 },
{ name: "Name", type: "text", width: 50},
{ type: "control", modeSwitchButton: false, deleteButton: false }
]
});
$(".config-panel input[type=checkbox]").on("click", function() {
var $cb = $(this);
$("#jsGrid").jsGrid("option", $cb.attr("id"), $cb.is(":checked"));
});
});
</script>
but I think it's not secure, how could I make it more secure?
I was having the same issue. However once I added the return to $.ajax line all I get is blank lines but the grid is trying to render something. See image below.
PHP Code Below:
$sql = "SELECT e.estimateid, e.customerid, e.compid, cu.first_name,cu.last_name,e.reference_num, e.estimate_date, e.expiry_date, e.hours, e.sales_person, e.project_name
FROM estimates AS e INNER JOIN company AS c ON e.compid = c.compid
INNER JOIN customers AS cu ON e.customerid = cu.customerid";
$resultsE = $conn->query($sql);
$rows = array();
while ($r = $resultsE->fetch_assoc()){
$rows[] = $r;
}
$data = array($rows);
}
//header("Content-Type: application/json"); //If I uncomment this line the Grid says No Results.
echo json_encode($data);
JS Code Below:
$(function() {
$("#jsGrid").jsGrid({
height: "90%",
width: "98%",
filtering: true,
inserting: false,
editing: false,
sorting: true,
paging: true,
autoload: true,
pageSize: 10,
pageButtonCount: 5,
//deleteConfirm: "Do you really want to delete client?",
controller: {
loadData: function(filter) {
return $.ajax({url: "/js/jsgrid/estimates/index.php",data: filter });
},
/*insertItem: function(item) {
return $.ajax({
type: "POST",
url: "/estimates/",
data: item
});
},
updateItem: function(item) {
return $.ajax({
type: "PUT",
url: "/estimates/",
data: item
});
},
deleteItem: function(item) {
return $.ajax({
type: "DELETE",
url: "/estimates/",
data: item
});
}*/
},
fields: [
{ name: "estimateid", type: "number", width: 10, title: "EstId" },
{ name: "customerid", type: "number", width: 10, title: "CustId" },
{ name: "compid", type: "number", width: 10, title: "CompId"},
{ name: "first_name", type: "text", width: 50, title: "First Name" },
{ name: "last_name", type: "text", width: 50, title: "Last Name" },
{ name: "reference_num", type: "text", width: 12, title: "Ref.#" },
{ name: "estimate_date", type: "text", width: 12, title: "Est. Date" },
{ name: "expiry_date", type: "text", width: 12, title: "Exp. Date" },
{ name: "hours", type: "number", width: 10, title: "Hours" },
{ name: "sales_person", type: "text", width: 50, title: "Sales" },
{ name: "project_name", type: "text" , width: 50, title: "Project"},
{ type: "control" }
]
});
});

Echo value from database to selectize.js with php

I'm trying to echo out value from database with php for selectize.js.
Html code
<select id="type" placeholder="Type" name="type" required>
<!-- This option help to selected value from DB -->
<!--<option value="<?php echo $dataFromDB['type'] ?>" selected></option>-->
</select>
<button id="someType">Add Option</button>
Js code (example from selectizejs (with change))
var $select = $('#type').selectize({
maxItems: 1,
valueField: 'id',
labelField: 'days',
searchField: 'days',
options: [{
id: '1',
days: '5 days'
}, {
id: '2',
days: '2 days'
}, {
id: '3',
days: '1 days'
}],
create: true
});
var control = $select[0].selectize;
$('#someType').on('click', function () {
control.addOption({
id: '4',
days: 'New Days'
});
});
How to automatically add option from database value and set as selected option?
jsfiddle link
Note: I could echo out the value to option if there's a match between database value and options value.
Thanks in advanced.
Like this? http://jsfiddle.net/2zyp8jxn/1/
control.setValue("4");
Create a variable with php:
$php_test = "control.addOption({
id: '".$dataFromDB['type']."',
hari: '".$dataFromDB['type']."'
});
control.setValue('".$dataFromDB['type']."');
";
and add this jquery code
var control = $select[0].selectize;
$(function() {
<?php echo 'var someOptions ='. $php_test ?>
});
I dont know if create a variable someOptions is necessary or not but it works for me.
Thanks

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

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

Categories

Resources