dojo.xhrGet Not Sending any Data - php

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?

Related

Load data from database to set highchart X-axis with php json data

new to this and (almost) desperate. in below code i want to set $rows1['date'][] = $data['tanggal']; data as X-Axis in highchart :
$(function () {
var chart;
$(document).ready(function() {
getAjaxData(1);
var val = location.search.split('proyek=')[1]
getAjaxData(val);
function getAjaxData(proyek){
$.getJSON("src/json/data.php", {proyek: proyek}, function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve-proyek',
type: 'column'
},
title: {
text: ''
},
credits: {
enabled: false,
},
subtitle: {
text: ''
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
title: {
text: ''
},
},
xAxis: {
type: 'datetime',
labels: {
formatter: function ( ){
return Highcharts.dateFormat('%Y-%m-%d', this.value);
},
},
},
tooltip:{
formatter: function() {
return '<b>' + this.series.name + '</b><br/>' +
Highcharts.numberFormat(this.y, 2) +' %';
},
},
plotOptions: {
column: {
dataLabels: {
enabled: true,
format: '{point.y:,.2f}'+'%',
}
},
},
series: json
});
});
};
});
});
my data.php :
<?php
header("Content-type: application/json");
require_once "database.php";
$db = new database();
$mysqli = $db->connect();
$proyek = $_GET['proyek'];
$sql = "SELECT fren_pr FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows = array();
$rows['name'] = 'Rencana';
$rows['color'] = '#50B432';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows['data'][] = array($data['fren_pr'],);
}
$sql = "SELECT freal_pr, tanggal FROM data_proyek WHERE kode_proyek = '$proyek'";
$rows1 = array();
$rows1['name'] = 'Realisasi';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$rows1['data'][] = $data['freal_pr'];
$rows1['date'][] = $data['tanggal'];
}
$rslt = array();
array_push($rslt, $rows);
array_push($rslt, $rows1);
print json_encode($rslt, JSON_NUMERIC_CHECK);
$mysqli->close();
this is my json view :
I've spent a lot of time trying to solve it but haven't found a solution until now.
Is there an error in my php code?
hope someone will be kind enough to help, Thanks in advance.

Highchart not showing from JSON data

I'm trying to display a line chart with json data, but with there, $_GET from the json I have the chart doesn't appear, here's my code :
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("master/proyek/s-curve.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'scurve',
type: 'line'
},
credits: {
enabled: false
},
title: {
text: 'S-Curve Balai'
},
subtitle: {
text: ''
},
xAxis: {
categories: ['M1', 'M2', 'M3', 'M4']
},
yAxis: {
title: {
text: ''
},
plotLines: [{
value: 1,
width: 1,
color: '#808080'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'horizontal',
},
plotOptions: {
line: {
dataLabels: {
enabled: true,
distance: 100,
}
}
},
series: json,
});
});
});
});
and this my s-curve.php :
<?php
header("Content-type: application/json");
require_once "config/database.php";
$db = new database();
$mysqli = $db->connect();
$balai = mysqli_real_escape_string($mysqli, $_GET['balai']);
if ($balai == 'bl-1') {
$sql = "SELECT plan, actual FROM scurve1 ORDER BY id ASC";
} else if ($balai == 'bl-2') {
$sql = "SELECT plan, actual FROM scurve2 ORDER BY id ASC";
} else if ($balai == 'bl-3') {
$sql = "SELECT plan, actual FROM scurve3 ORDER BY id ASC";
}
$hasil = array();
$hasil['name'] = 'Plan';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$hasil['data'][] = $data['plan'];
}
$hasil1 = array();
$hasil1['name'] = 'Actual';
$result = $mysqli->query($sql);
while ($data = $result->fetch_assoc()) {
$hasil1['data'][] = $data['actual'];
}
$nilai = array();
array_push($nilai, $hasil);
array_push($nilai, $hasil1);
print json_encode($nilai, JSON_NUMERIC_CHECK);
$mysqli->close();
display my json from localhost/master/proyek/s-curve.php?balai=bl-1 :
Display Json Data
from my case above, can someone tell what error I can fix to be able to display the chart.

Filter ChartJS using data from PHP

I would like to filter my chart by month so I made a <select> input above it. The chart is showing properly but when I changed the month options, the data is not updating based on the value selected. Here's what I've done so far:
index.php
<div class="row form-group">
<select class="form-control col-lg-4" name="month">
<option selected="selected" style="display:none"><?php echo date("F");?></option>
<option value="9">September</option>
<option value="10">October</option>
</select>
</div>
<canvas id="chart"></canvas>
<script>
window.onload = function() {
$.ajax({
type: 'POST',
url: 'data.php ',
datatype: 'json',
success: function (result) {
var ctx = document.getElementById("chart").getContext("2d");
var mychart = new Chart(ctx,
{
type: 'bar',
data: JSON.parse(result),
options: {
scales: {
xAxes: [{ stacked: true }],
yAxes: [{ stacked: true }]
}
}
})
}
})};
</script>
data.php
<?php
$conn = mysqli_connect("localhost","root","","production");
$month = '';
if(isset($_POST["month"]))
{
$month = $_POST["month"];
} else {
$month = date('m');
}
$query = "SELECT finish_date,
SUM(CASE WHEN customer_type = 'customer_A' THEN order_qty ELSE 0 END) AS custom_A,
SUM(CASE WHEN customer_type = 'customer_B' THEN order_qty ELSE 0 END) AS custom_B,
SUM(CASE WHEN customer_type = 'customer_C' THEN order_qty ELSE 0 END) AS custom_C
FROM production WHERE MONTH(finish_date) = ".$month." GROUP BY finish_date ORDER BY finish_date ASC";
if ($stmt = $conn->prepare($query)) {
$stmt->execute();
$stmt->bind_result($date, $custom_A, $custom_B, $custom_C);
$labels = array();
$data_A = array();
$data_B = array();
$data_C = array();
while ($stmt->fetch()) {
$labels[] = $date;
$data_A[] = $custom_A;
$data_B[] = $custom_B;
$data_C[] = $custom_C;
}
$stmt->close();
}
$datasets_A = array('label'=>"A",'data'=> $data_A,'backgroundColor'=>"#D6E9C6");
$datasets_B = array('label'=>"B",'data'=> $data_B,'backgroundColor'=>"#FAEBCC");
$datasets_C = array('label'=>"C",'data'=> $data_C,'backgroundColor'=>"#EBCCD1");
$data = array('labels'=>$labels, 'datasets'=> array($datasets_A,$datasets_B,$datasets_C));
echo json_encode($data);
?>
How can I make it work? I must have miss something but not sure what it is since I'm not getting any error message.
You need to write change event so that whenever select-box is change the value will be send to your backend and the updated json data will send back as response which you will update in your chart .
Jquery code :
window.onload = function() {
update(); //call your function to update chart
}
//onchange of select
$("select[name=month]").on("change", function() {
var month = $(this).val() //get value of select
update(month); //call to update
})
function update(month) {
var value;
//if null
if (month == null) {
value = "default"; //send some dummy data
} else {
value = month; //send actual month
}
$.ajax({
type: 'POST',
url: 'data.php ',
data: {
month: value //send value to backend
},
datatype: 'json',
success: function(result) {
//update chart datas
var ctx = document.getElementById("chart").getContext("2d");
var mychart = new Chart(ctx, {
type: 'bar',
data: JSON.parse(result),
options: {
scales: {
xAxes: [{
stacked: true
}],
yAxes: [{
stacked: true
}]
}
}
})
}
})
}
And only change in php code you need to make is here :
if(isset($_POST["month"]) && $_POST["month"] != "default" ){
$month = $_POST["month"];
} else {
$month = date('m');
}

how to update variable dynamically of currency rate WITH php/json/ajax

I would like to know how to update variable dynamically of currency rate WITH php/AJAX/json that $CurrencyValue (the currency value from yahoo finance) will update only if the variable is different than it was before.
For example:
on 01/01/2016 10:00 USDINR gate was 67.454.
1/01/2016 10:01 USDINR gate was 67.104 (the variable $CurrencyValue be updated).
1/01/2016 10:02 gate of USDINR remains 67.104 (the variable $CurrencyValue not be updated).
1/01/2016 10:03 USDINR gate was 67.024 (so the variable $CurrencyValue be updated).
It is important the page will not refreshed, only the variable $CurrencyValue also if the variable changed I would like to get The exact date.
<?php
$from = 'USD'; $to = 'INR'; $url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X'; $currencyValue = 0; $handle = fopen($url, 'r'); if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$currencyValue = $data[1];
}
fclose($handle);
} $date = date('l jS \of F Y h:i:s A');
?>
Value of 1 USDINR is <?php echo $currencyValue. ' - ' .$date; ?>
Thank you
EDIT
I have a code of euro-dollar exchange via YAHOO FINANCE works with PHP / AJAX. My question is how to integrate the data released chart works with CHARTS.JS
labels: ["2016-06-02 12:41:06", "2016-06-02 12:41:08"],
datasets: [{
label: "My Third dataset - No bezier",
data: [1.1200,1.1205],
lineTension: 0,
fill: false,
}]
{"rate":"1.1200","time":"2016-06-02 12:41:06"}
{"rate":"1.1205","time":"2016-06-02 12:41:08"}
{"rate":"1.1199","time":"2016-06-02 12:41:10"}
{"rate":"1.1199","time":"2016-06-02 12:41:12"}
The Code:
<script src="Chart.bundle.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<style>
canvas {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
<?php
if(isset($_GET['fetchOnly'])){
$from = 'eur';
$to = 'usd';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$response = array();
$handle = fopen($url, 'r');
if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$response['rate'] = $data[1];
$response['time'] = date("Y-m-d H:i:s");
}
fclose($handle);
}
echo json_encode($response);
die();
}
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();
function fetchRate() {
// create the new AJAX Object
xmlhttp = new XMLHttpRequest();
// this handles the request
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
// if the request came back successfully
if(xmlhttp.status == 200){
// write the response to a div
div = document.getElementById("responseText")
div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
}else{
// if the request had an error
div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
}
// rerun this function to fetch updates
setTimeout(fetchRate,1000);
}
};
// open the AJAX Object
xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
// send the AJAX request
xmlhttp.send();
}
</script>
<div style="width:100%;">
<canvas id="canvas"></canvas>
</div>
<script>
var MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var randomScalingFactor = function() {
return Math.round(Math.random() * 100 * (Math.random() > 0.5 ? -1 : 1));
};
var randomColorFactor = function() {
return Math.round(Math.random() * 255);
};
var randomColor = function(opacity) {
return 'rgba(' + randomColorFactor() + ',' + randomColorFactor() + ',' + randomColorFactor() + ',' + (opacity || '.3') + ')';
};
var config = {
type: 'line',
data: {
labels: ["2016-06-02 12:36:05", "2016-06-02 12:37:05"],
datasets: [{
label: "My Third dataset - No bezier",
data: [1,2],
lineTension: 0,
fill: false,
}]
},
options: {
responsive: true,
legend: {
position: 'bottom',
},
hover: {
mode: 'label'
},
scales: {
xAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Month'
}
}],
yAxes: [{
display: true,
scaleLabel: {
display: true,
labelString: 'Value'
}
}]
},
title: {
display: true,
text: 'Chart.js Line Chart - Legend'
}
}
};
$.each(config.data.datasets, function(i, dataset) {
var background = randomColor(0.5);
dataset.borderColor = background;
dataset.backgroundColor = background;
dataset.pointBorderColor = background;
dataset.pointBackgroundColor = background;
dataset.pointBorderWidth = 1;
});
window.onload = function() {
var ctx = document.getElementById("canvas").getContext("2d");
window.myLine = new Chart(ctx, config);
};
$('#randomizeData').click(function() {
$.each(config.data.datasets, function(i, dataset) {
dataset.data = dataset.data.map(function() {
return randomScalingFactor();
});
});
window.myLine.update();
});
$('#addDataset').click(function() {
var background = randomColor(0.5);
var newDataset = {
label: 'Dataset ' + config.data.datasets.length,
borderColor: background,
backgroundColor: background,
pointBorderColor: background,
pointBackgroundColor: background,
pointBorderWidth: 1,
fill: false,
data: [],
};
for (var index = 0; index < config.data.labels.length; ++index) {
newDataset.data.push(randomScalingFactor());
}
config.data.datasets.push(newDataset);
window.myLine.update();
});
$('#addData').click(function() {
if (config.data.datasets.length > 0) {
var month = MONTHS[config.data.labels.length % MONTHS.length];
config.data.labels.push(month);
$.each(config.data.datasets, function(i, dataset) {
dataset.data.push(randomScalingFactor());
});
window.myLine.update();
}
});
$('#removeDataset').click(function() {
config.data.datasets.splice(0, 1);
window.myLine.update();
});
$('#removeData').click(function() {
config.data.labels.splice(-1, 1); // remove the label first
config.data.datasets.forEach(function(dataset, datasetIndex) {
dataset.data.pop();
});
window.myLine.update();
});
</script>
Thank you.
<?php
if(isset($_GET['fetchOnly'])){
$from = 'USD';
$to = 'INR';
$url = 'http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s='. $from . $to .'=X';
$response = array();
$handle = fopen($url, 'r');
if ($handle) {
while (($data = fgetcsv($handle, 1024, ',', '"')) !== FALSE)
{
$response['rate'] = $data[1];
$response['date'] = $data[2];
$response['time'] = $data[3];
}
fclose($handle);
fclose($handle);
}
echo json_encode($response);
die();
}
?>
<div id="responseText"></div>
<script>
// run the function, it will re-run itself
fetchRate();
function fetchRate() {
// create the new AJAX Object
xmlhttp = new XMLHttpRequest();
// this handles the request
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
// if the request came back successfully
if(xmlhttp.status == 200){
// write the response to a div
div = document.getElementById("responseText")
div.innerHTML = div.innerHTML + '<br />'+ xmlhttp.responseText;
}else{
// if the request had an error
div.innerHTML = div.innerHTML + '<br />Error fetching rates error code : '+xmlhttp.status;
}
// rerun this function to fetch updates
setTimeout(fetchRate,3000);
}
};
// open the AJAX Object
xmlhttp.open("GET", "<?= basename(__FILE__) ?>?fetchOnly", true);
// send the AJAX request
xmlhttp.send();
}

Ext Tree, Data is displayed in console, but does not display on page

My data is displayed in console, but does not display in ExtJs tree?
My php file
$data = array();
$sql = "";
if (!isset($_POST['node'])) {
// first select the top node that have no parent
$sql = "SELECT id_no,value_data FROM extjs_tree WHERE parent IS NULL";
} else {
// select data with parent_id = $_POST['node']
$sql = "SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $_POST['node'] ."'";
}
$q = mysql_query($sql);
while ($r = mysql_fetch_array($q)) {
// check if have a child node
$qq = mysql_query("SELECT id_no, value_data FROM extjs_tree WHERE parent = '". $r['id'] ."'");
if (mysql_num_rows($qq) > 0) {
// if have a child
$r['leaf'] = false;
$r['cls'] = 'folder';
} else {
// if have no child
$r['leaf'] = true;
$r['cls'] = 'file';
}
$data[] = $r;
}
echo json_encode($data);
My JS file
Ext.require([
'Ext.tree.*',
'Ext.data.*',
'Ext.tip.*'
]);
Ext.onReady(function() {
Ext.QuickTips.init();
var store = Ext.create('Ext.data.TreeStore', {
proxy: {
type:'ajax',
actionMethods:'post',
url:'get-nodes.php'
},
root: {
text: 'Root Node',
id: 'root_node',
expanded: true
},
folderSort: true,
sorters: [{
property:'text',
direction:'ASC'
}]
});
var tree = Ext.create('Ext.tree.Panel', {
store: store,
renderTo: 'tree_el',
height: 300,
width: 250,
title: 'Products Display'
});
});
I am getting the tree properly, I can see the data in the console. But I cannot see ExtJs displaying the values??
My present result
My expected result should be
In your case you can also add following field to your store:
{
name: 'text',
mapping: 'value'
}
Every item of response has to have text field in it. As I can see from your request-response images You don't send text field. Response should be looking like the following one:
[{
"id": 2,
"text": "Fruits", // this field is required
...
},
...
]

Categories