using json with jquery for jtables? - php

I am using jtables (http://www.jtable.org), but one of the options to create a combobox (dropdown menu) is such:
Branch: {
title: 'Branch',
type: 'list',
options: {
'1': 'Auckland',
'2': 'Queensland'
}
}
I want to be able to use a mysql query (JSON'ed?) for my "options" instead of hardcoding it. Any ideas?

Branch:{
title: 'Page Name',
width: '30%',
options: 'FieldNameLoader.php?action=Branch',
list :true
}
if($_GET["action"] == "Branch") {
$result = mysql_query("SELECT * from tblPagelist ORDER BY PageName ASC;");
$rows = array();
while ($row = mysql_fetch_array($result)) {
$eil = array();
$eil["DisplayText"] = $row[1];
$eil["Value"] = $row[0];
$rows[] = $eil;
}
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['Options'] = $rows;
print json_encode($jTableResult); }

Use PHP's json_encode with mysql_fetch_array
PHP
while($row = mysql_fetch_array($query)) {
$options[$row['id']] = $row['name'];
}
$options = json_encode($options);
JSON
Branch: {
title: 'Branch',
type: 'list',
options: <?=$options?>
}

What I do is on the php side I query everything and put it into an array and then echo it to the javascript page:
Branch: {
title: 'Branch',
type: 'list',
options: <?php echo json_encode($branchArray)?>
}

Related

How to loop in PHP and display all rows

So I have this problem in looping in PHP, I can't seem to display, it only displays the first row. I want to display all 18 places and at the same time all places have different counts/data each. I think I'm missing a lot in PHP.
//This part of code displays the names and counts the met conditions
$sql = "SELECT b.name as brgy0,(SELECT COUNT(brgy_id) FROM tbl_fire_info where YEAR(date_of_report)=$year AND MONTH(date_of_report)=$smonth and status=1 AND brgy_id=b.barangayID) as cnt FROM tbl_barangay as b";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$numData = $row['cnt'];
$brgyData = $row['brgy0'];
//This part of code displays the data in the graph, I decided to loop it 18 times
new Chart(document.getElementById("bar-chart-grouped"), {
type: 'bar',
data: {
labels: ['<?php if(isset($_POST['submit'])){echo $haz;} ?>'],
datasets: [ //barangays
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
{
label: "<?php if(isset($_POST['submit'])){echo $brgyData;} ?>",
backgroundColor: "#3e95cd",
data: [<?php if(isset($_POST['submit'])){echo $numData;} ?>]
}
<?php
echo ",";
}
}else {
echo "0 results";
}
?>
]
},
options: {
title: {
display: true,
text: 'Number of reports'
}
}
});

Getting correct value of num_rows back AJAX/JSON

I have a notification system that out puts the right value of 1 and updates the div accordingly when a user posts one on my wall.
{
"num":1,
"notification_id":"640",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=515",
"notification_triggeredby":"85",
"notification_status":"1"
}
But if a user posts twice it does nothing and doesn't update at all.
{
"num":1,
"notification_id":"641",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=516",
"notification_triggeredby":"85",
"notification_status":"1"
}
{
"num":1,
"notification_id":"642",
"notification_content":"Lucy Botham posted a status on your wall",
"notification_throughurl":"singlepoststreamitem.php?streamitem_id=517",
"notification_triggeredby":"85",
"notification_status":"1"
}
CLIENT SIDE
$user1_id=mysqli_real_escape_string($mysqli,$_SESSION['id']);
$call="select MAX(notification_id) AS notification_id ,notification_status,notification_targetuser,notification_triggeredby,notification_throughurl from notifications WHERE notification_targetuser='$user1_id' AND notification_status='1'";
$chant=mysqli_query($mysqli,$call) or die(mysqli_error($mysqli));
while($notification=mysqli_fetch_array($chant)){
?>
<script type="text/javascript">
var notification_id="<?php echo $notification['notification_id']?>";
var notification_targetuser="<?php echo $notification['notification_targetuser']?>";
var notification_triggeredby="<?php echo $notification['notification_triggeredby']?>";
function loadIt() {
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&notification_targetuser="+notification_targetuser+"&notification_triggeredby="+notification_triggeredby,
dataType:"json",
success: function(data){
if(data.notification_stream=1){
$("#notif_ui"+notification_id).prepend('<div class="notif_text"><div id="notif_actual_text-" class="notif_actual_text"><img border="1" src="userimages/cropped'+data['notification_triggeredby']+'.jpg" onerror=this.src="userimages/no_profile_img.jpeg" width="40" height="40" ><br />'+data['notification_content']+' <br />'+data['notification_time']+'<br/></div></div></div><hr/>');
i = parseInt($("#mes").text()); $("#mes").text((i+data.num));
if(!data.notification_id.length) {
//no results...
return;
}
notification_id = data.notification_id;
}
}
});
}
setInterval(loadIt, 10000);
</script>
<? } ?>
SERVER SIDE
$json = array();
$com=mysqli_query($mysqli,"SELECT * from notifications WHERE notification_targetuser='$idw' AND notification_triggeredby='$ide' AND notification_status='1' ORDER BY notification_id")or die($mysqli);
while($row = mysqli_fetch_assoc($com)){
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json['notification_id'] = $row['notification_id'];
$json['notification_content'] = $row['notification_content'];
$json['notification_throughurl'] = $row['notification_throughurl'];
$json['notification_triggeredby'] = $row['notification_triggeredby'];
$json['notification_status'] = $row['notification_status'];
echo json_encode($json);
}}
$sql = "UPDATE notifications SET notification_status = '2' WHERE notification_targetuser='$idw'";
$go = mysqli_query($mysqli,$sql) or die(mysqli_error($mysqli));
You're echoing the JSON results inside a loop, so if the loop executes more than once, the final result is not valid JSON data. It's just multiple chunks of JSON.
while($row = mysqli_fetch_assoc($com)){
$id = $row['notification_id'];
$num = mysqli_num_rows($com);
if($num){
$json['num'] = 1;
}else{
$json['num'] = 0;
}
$json[$id]['notification_id'] = $row['notification_id'];
$json[$id]['notification_content'] = $row['notification_content'];
$json[$id]['notification_throughurl'] = $row['notification_throughurl'];
$json[$id]['notification_triggeredby'] = $row['notification_triggeredby'];
$json[$id]['notification_status'] = $row['notification_status'];
}
echo json_encode($json);
Then you'll need to adjust your Javascript to expect an array instead of a flat object.

dojo.xhrGet Not Sending any Data

I want to take dojo Get data from ajax to php
Dojo passing parameter i couldn't take it in php class.
passing the cpa is not pass to php file..
This is my code :
globalHandlers: {
doVsatEvents: function(vsatId, network, cpa) {
// retrieve the events via xml
dojo.xhrGet ({
url: "includes/vsat_events.php?",
handleAs: "xml",
preventCache: true,
content: {
network: network,
cpa: cpa
},
load: function(response, args) {
var temp = response.getElementsByTagName("event");
var eventsItems =[];
alert (temp.length);
for (var i = 0; i < temp.length; i++) {
var event = [];
event = [];
event['id'] = temp[i].getAttribute(['id']);
event['nms'] = temp[i].getAttribute(['nms']);
event['status'] = temp[i].getAttribute(['status']);
event['date'] = temp[i].getAttribute(["date"]);
event['time'] = temp[i].getAttribute(["time"]);
event['description'] = temp[i].getAttribute(["description"]);
alert (events['description']);
eventsItems.push(event);
}
var eventsGridData = {
identifier: 'id',
items: eventsItems
};
// build a floating pane
var fPane = SM.util.skymapFloatingPane("Events", "eventsFPID_" + SM.getNextId());
var eventsStore = new dojo.data.ItemFileReadStore({
data: eventsGridData,
clearOnClose: true
});
// set the layout structure: 720px
// scrollbar is 14px wide
var eventsLayout = [{
field: 'id',
name: 'ID',
width: '60px'
},{
field: 'nms',
name: 'NMS',
width: '55px'
},{
field: 'status',
name: 'Severity',
width: '60px'
},{
field: 'date',
name: 'Date',
width: '100px'
},{
field: 'time',
name: 'Time',
width: '90px'
},{
field: 'description',
name: 'Description',
width: '400px'
}];
// create a new grid:
var eventsGrid = new dojox.grid.DataGrid({
query: {
id: '*'
},
store: eventsStore,
clientSort: true,
rowSelector: '20px',
structure: eventsLayout
}, document.createElement('div'));
// append the new grid to the div "gridContainer4":
fPane.set('content', eventsGrid);
//document.body.appendChild(fPane.domNode);
fPane.startup();
fPane.show();
}
});
},
This is my PHP code :
<?php
chdir('../../../');
include_once("./include/auth.php");
// Start XML file, create parent node
$doc = new DOMDocument;
$node = $doc->createElement("events");
$parnode = $doc->appendChild($node);
$query = "SELECT * FROM `skymap_1_nms_events`";
$query .= " WHERE `cpa` = ".$_GET['cpa'];
$query .= " ORDER BY `id` DESC";
//print $query;
$result = mysql_query ($query);
header("Content-type: text/xml");
while($row = mysql_fetch_assoc($result)){
$status = $row['severity'];
if ($status == 3){
$status = "normal";
} elseif($status == 1) {
$status = "disabled";
} elseif($status == 2) {
$status = "unmanaged";
} elseif($status == 4) {
$status = "warning";
} elseif($status == 5) {
$status = "minor";
} elseif($status == 6) {
$status = "major";
} elseif($status == 7) {
$status = "critical";
} else {
$status = "unknown";
}
$childnode = $doc->createElement("event");
$newnode = $parnode->appendChild($childnode);
$newnode->setAttribute("id", $row['id']);
$newnode->setAttribute("nms", $row['reporting_nms']);
$newnode->setAttribute("status", $status);
$newnode->setAttribute("date", $row['date']);
$newnode->setAttribute("time", $row['time']);
$newnode->setAttribute("description", $row['description']);
}
$xmlfile = $doc->saveXML();
echo $xmlfile;
?>
any help?

PHP - Remove last char in while

i know many function to remove char in php. but i'm confused to remove this :
i want remove "," from
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
while($row = mysql_fetch_array($result))
{
$data= "['$row[keyword]', $row[jumlah]],<br>";
echo $data;}
?>
will give result :
['Smartfren', 1],
['Telkomsel', 1],
i want the output like :
['Smartfren', 1],
['Telkomsel', 1]
How to do that?
big thanks for the response.
UPDATE
based on #orangpill answer say i have printed data like :
['ABC', 6597],
['XYZ', 4479],
['PQR', 2075],
['Others', 450]
i want to make a chart, say the code of js chart have to be like :
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
based on #orangepill now my code :
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data);
?>
<script type="text/javascript">
$(function () {
$('#container').highcharts({
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Presentase Sentimen Positif'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ Math.round(this.percentage) +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Nilai',
data: [
<?php while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data); ?>
]
}]
});
});
</script>
It might make sense for you to do this by building an array and imploding it when you want to output
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = "['$row[keyword]', $row[jumlah]]";
}
echo implode(",<br/>", $data);
?>
If you are formatting for this data for consumption by javascript a better approach would be to use json_encode.
<?php
include '../config/settings.php';
$query = "SELECT keyword,count(*) AS jumlah
FROM search GROUP BY keyword ASC";
$result = mysql_query($query);
$data = array();
while($row = mysql_fetch_array($result))
{
$data[] = array($row[keyword], (int)$row[jumlah]);
}
echo "var data = ".json_encode($data).";";
?>
You can also use the substr() function:
$data = "";
while($row = mysql_fetch_array($result)) {
$data .= "['$row[keyword]', $row[jumlah]],<br>";
}
$data = substr($data, 0, -5);
echo $data;
rtrim():
$data = rtrim($data, ',');
or, in your particular example, substr:
$data = substr($data, 0, -5);
to remove the "" as well.

Formatting json data to work in Flot

Is there anyway to convert this json data:
[
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
]
to like this:
{
"data": [[1999, 3.0], [2008, 0.9]]
}
Check type of values ("3.0" and 3.0, string and integer).
I am having hard time to figure this out, or is it even possible.
This is how I get the json data:
I have "data" table in my database where are "year" and "value" columns, I get them from database like:
$sql = mysql_query("SELECT * FROM data");
$rows = array();
while($r = mysql_fetch_assoc($sql)) {
$rows[] = $r;
}
$encodedJson = json_encode($rows);
$encodedJson = json_encode($rows);
print $encodedJson;
I am trying to create a graph from my data, and json data must be formated properly to work in Flot.
All help is appreciated!
You could map your array of objects into an multidimensional array:
var mapped = originalData.map(function (obj) {
return [ parseInt(obj.year, 10), parseFloat(obj.value) ];
});
var newData = {
data: mapped
};
Possible solution
var a = [
{
"year":"1999",
"value":"3.0"
},
{
"year":"2008",
"value":"0.9"
}
];
var b = [];
$.each(a, function(_index, _item){
var c = [_item["year"], _item["value"]];
b.push(c);
});
console.log(b)
try this.
PHP:
$sql = mysql_query("SELECT * FROM data");
$rows = $sql->results_array();
$return_args = array();
foreach($rows as $row){
$tmp[0] = $row['year'];
$tmp[1] = $row['value'];
array_push($return_args,$tmp);
}
$encodedJson = json_encode($return_args);
print $encodedJson;

Categories