Wrong representation of php data with jqplot - php

I have problems to create an array which is evaluated correctly by jqplot.
If i try it like this, i have an x-axis range from -5 to 95 but with the correct line.
Actually i would expect a chart with x-axis from 0 to 30.
With firebug i can check with typeof that params is an object (array).
Where is the failure?
Here is my getPlotData.php with some dummy data:
$temp = array();
for( $i=0; $i<30; $i++ ){
$temp[] = "[" . $i . "," . ($i*5) . "]";
}
$return['line'] = "[" . implode(',', $temp . "]";
die(json_encode($return));
And here is my ajax function which is calling the createPlot-function:
$.ajax({
type: "GET",
dataType: "json",
url: "getPlotData.php?rand=" + new Date(),
data: data,
cache: false,
success: function(data) {
var params = eval(data['line']);
createPlot(params);
}
});
function createPlot(params){
plot1 = $.jqplot('plot_data', [params], {
series:[{showMarker:true}],
markerOptions: { style:'circle' },
axesDefaults:{
tickRenderer: $.jqplot.CanvasAxisTickRenderer ,
tickOptions: {
fontSize: '14px',
textColor: "#fff"
}
},
axes:{
xaxis:{
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
label:'Tag',
tickOptions:{
},
labelOptions: {
fontSize: '13pt',
textColor: '#FFFFFF'
}
},
yaxis:{
label:'Anzahl',
labelRenderer: $.jqplot.CanvasAxisLabelRenderer,
tickOptions:{
},
labelOptions: {
fontSize: '13pt',
textColor: '#FFFFFF'
}
}
}
});

Currently you are using implode and json_encode. I guess, that manually creating JSON might produce some kind of error in the output. (Like double encoding the JSON data.)
It should work if you only add the data to the array first and then json_encode whole dataset.
<?php
$temp = array();
for( $i=0; $i < 30; $i++ ) {
$temp[] = array( $i, $i*5 );
}
$return['line'] = $temp;
die( json_encode( $return ) );

Related

Getting a JSON from a Ajax request and creating a polygon layer in Leaflet

I need some help with a script, i have an ajax request that returns a GeoJSON
Images:
JSON Format
"id_map": "2",
"description": "AC1",
"geojson": {a GeoJSON coordinate }
"file": "AC1.geojson"
I can use AJAX JSON Leaflet (plugin( to create a polygon layer using the JSON value file ex (ac1.geojson) and point it up to a folder with the GeoJSON files (ex. geojson), but i have the same GeoJSON saved as a text variable in a database and i want to use it besides the file because of the risk of losing the files, so i recover it (i use GeoJson.io to validate the geojson and copy paste it in a column in my database) using a database connection and then i JSON encode it, but i am unable to use it. And I'm having problems with the format that comes out from the PHP.
$(document).ready(function() {
document.body.onload = function() {
var tiles = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 20,
minZoom: 13,
attribution: 'x'
}),
latlng = L.latLng(-32.0312422, -52.0917713);
var mymap = L.map('mapid', {
center: latlng,
zoom: 18,
layers: [tiles]
});
L.marker([-32.0312422, -52.0917713]).addTo(mymap);
function popUp(f, l) {
var out = [];
if (f.properties) {
for (key in f.properties) {
out.push(key + ": " + f.properties[key]);
}
l.bindPopup(out.join("<br />"));
}
}
var j_url = "somephp.php";
var results = $.ajax({
url: j_url,
dataType: 'json',
cache: false,
success: AjaxSucceeded,
error: AjaxFailed
});
function AjaxSucceeded(results) {
console.log("Data successfully loaded.");
alert("OK");
$.each(results, function(index, value) {
var geojsonTESTE = {
"type": "FeatureCollection",
"features": [{
"type": "Feature",
"properties": {},
"geometry": {
"type": "Polygon",
"coordinates": [
[
[-52.101760, -32.031909],
[-52.102275, -32.028598],
[-52.100794, -32.028435],
[-52.099206, -32.029053],
[-52.097554, -32.029362],
[-52.097511, -32.029672],
[-52.096760, -32.029672],
[-52.096696, -32.029544],
[-52.095795, -32.029617],
[-52.094142, -32.029835],
[-52.088585, -32.030672],
[-52.088392, -32.030763],
[-52.088027, -32.034656],
[-52.101631, -32.032145],
[-52.101760, -32.031909]
]
]
}
}]
};
var geoObject = JSON.parse(value.geojson);
L.geoJSON(geojsonTESTE).addTo(mymap);
L.geoJSON(features).addTo(mymap);
//With Leaflet Ajax e Files
//j_url = "json/"+value.file;
//var jsonTest = new L.GeoJSON.AJAX([j_url]{onEachFeature:popUp}).addTo(mymap);
});
}
function AjaxFailed(results) {
console.log("ERROR AJAX");
alert("ERRO");
}
$.when(results).done(function() {
});
};
});
<?php
header('Content-Type: application/json');
$connStr = { database connection string }
$conn = pg_connect($connStr);
$result = pg_query($conn, "select * from mapas");
$qtd = pg_num_rows($result);
$res = "[";
if($qtd > 0){
$i = 0;
foreach(pg_fetch_all($result) as $row)
{
$x = $row['geojson'];
$patterns = array ('/[^A-Za-z0-9\-\,\"\:\{\}\[\]]/');
$replace = array ('');
$desc = preg_replace($patterns, $replace,$x);
$desc = str_replace('\"', '"', $desc, $count);
$data['id_map'] = $row['id_map'];
$data['description'] = $row['description'];
$data['geojson'] = $desc;
$data['file'] = $row['file'];
$map = json_readable_encode($data,null,true);
$res .= $map;
if($i < $qtd -1 ){
$res .= ",";
}
$i++;
}
}
$res .= "]";
echo trim($res);
pg_free_result($result);
pg_close();
?>

how to add row as html to BootStrap Plugin DataTable?

Is there a way to add row as html to datatable? I understand that the suggested way of doing it is this:
$('#addRow').on( 'click', function () {
t.row.add( [
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
] ).draw( false );
counter++;
} );
But I have a complex JSON input and I want to pre process it in PHP. Is it doable or even possible?
EDIT:
So instead of doing the code above:
t.row.add(resultfromphpserverwithalltherows);
UPDATE:
JSON output
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
and sometimes:
{"student":[{"id":"2008-161","name":"Joseph Taylor","age":"20","status":"married","address":"USA","subjects":[{"math":"90","science":96,"history":99,"literature":93,"pe":"96"}],"remarks":"passed","othersubjects":[{"applied math":"90","general science":96,"world history":99,"literature":93,"pe":"96"}],"remarks":"passed"}
So I can't really define the columns because the JSON output is dynamic and that's why I want to preprocess it in PHP first.
No matter how you approach this, there's going to be some significant data-formatting required.
Best approach for what you're asking: use DataTables server-side tools.
It requires including some additional components, but will simplify the javascript down to:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
} );
...with a little tweaking, you can simplify that further:
$(function(){
var dt = new dataTableAuto();
dt.load();
});
function dataTableAuto() {
this.params = {
"processing": true,
"serverSide": true,
"ajax": "../server_side/scripts/server_processing.php"
};
this.load = function() {
$('#example').DataTable( this.params );
}
}
php ajax server to send raw JSON as a single row
Simply send an ajax request to php which includes the counter, then respond with a json array matching what you want to build.
Javascript snippet
counter = 0;
$.ajax({
url: '[your url]',
type: 'post',
data: {"counter":counter},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.row.add(JSON.parse(response)).draw( false );
counter++;
},
});
php Snippet
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$counter = $data['counter'];
$totalRows = 10;
for( $i = 0; $i < $totalRows; $i++) {
$result[] = $counter .".". $i;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
DataTables pure AJAX approach
javascript
$(function(){
t = $('#example');
$.ajax({
url: '[your url]',
type: 'post',
data: {"classID":12},
contentType: "application/json",
dataType: 'json',
success: function(response){
t.DataTable( JSON.parse(response) );
},
});
});
php
$jsonString = file_get_contents('php://input');
$data = json_decode($jsonString);
$classID = intval($data['classID']);
$cols = array('Name', 'Position', 'Score');
foreach ( $cols as $colName ) {
$entry = new stdClass();
$entry->title = $colName;
$result['columns'][] = $entry;
}
$result = // some query [ex: get rows by class id]
foreach( $result as $row) {
$thisRow = array();
foreach ( $cols as $colName ) {
$thisRow[] = $row['$colName']
}
$result['data'][] = $thisRow;
}
header('Content-Type: application/json', true, 200);
echo json_encode($result);
exit;
This should produce an object similar to:
{
data: [
['Joseph Taylor', '22', '90']
],
columns: [
{ title: "Name" },
{ title: "Position" },
{ title: "Score" }
]
}

How to send my MySQL data with PHP code to morris-data.js?

I got a problem how to make morris chart with data from MySQL database. I have made a php code with output like how JSON template can accepted to morris-data.js.
Here's my php code name cobaJson.php:
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
<?php
include_once("koneksi.php");
$query = "SELECT * FROM data_graph ORDER BY x ASC";
$result = mysql_query( $query );
while ( $row = mysql_fetch_assoc( $result ) )
{
$prefix = '';
echo "[<br />";
while ( $row = mysql_fetch_assoc( $result ) )
{
echo $prefix . " {<br />";
echo ' x: ' . $row['x'] . ',' . "<br />";
echo ' y: ' . $row['y'] . ',' . "<br />";
echo ' z: ' . $row['z'] . ',' . "<br />";
echo ' a: ' . $row['a'] . '' . "<br />";
echo " }";
$prefix = ",<br />";
}
echo "<br />]";
}
?>
And here's the output :
[ { x: 2012, y: 11, z: 6, a: 9 }, { x: 2014, y: 3, z: 3, a: 1 }, { x:
2015, y: 4, z: 7, a: 9 } ]
And I try to send this php code to my morris-data.js :
$(function() {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'cobaJson.php',
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})
();
Morris.Bar({
element: 'morris-bar-chart',
data: json,
xkey: 'x',
ykeys: ['y', 'z', 'a'],
labels: ['Series A', 'Series B', 'Series B'],
hideHover: 'auto',
resize: true
});
});
But it still not work, anyone can you help me?
In you cobaJson.php file, you should create a clean JSON object with json_encode as follows :
$array = array();
while ( $row = mysql_fetch_assoc( $result ) )
{
array_push(
$array,
array(
'x' => $row['x'],
'y' => $row['y'],
'z' => $row['z'],
'a' => $row['a']
)
);
}
echo json_encode($array);
Edit:
Since you said your json output from the php is ok, the issue should be located in your js file.
Add error function in your ajax object, just after success as follows:
$.ajax({
'async': false,
'global': false,
'url': 'cobaJson.php',
'dataType': "json",
'success': function (data) {
json = data;
}
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log(
'status:' + XMLHttpRequest.status +
', status text: ' + XMLHttpRequest.statusText
);
console.log(errorThrown);
}
});
and look at your console.
You have Closed the function in a Unexpected Way.
$(function() {
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'cobaJson.php',
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})
();
Change your last two lines into:
});
Hope It will Help You.

Having trouble passing data to Highcharts

I am trying to pull financial stock data of multiple companies from CSVs and display the data as separate series in a Highcharts/Highstocks line chart. I have the sources setup and I am able to pull data + convert to JSON, but I am having trouble passing the data off to Highcharts. I believe I am not using the most efficient method of preparing the data for Highcharts use, and I am hoping someone can give me direction on what I've done incorrectly. Please take a look at my code and make me aware of any inefficiencies or glaring errors you see.
PHP code:
date_default_timezone_set('America/Los_Angeles');
$stocks = array('MSFT' => 'http://ichart.finance.yahoo.com/table.csv?s=MSFT', 'AAPL' => 'http://ichart.finance.yahoo.com/table.csv?s=AAPL', 'FB' => 'http://ichart.finance.yahoo.com/table.csv?s=FB');
$stocks_data = array();
foreach ($stocks as $key=>$stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$varname = $key . '_data';
$$varname = array();
while ($line = fgetcsv($fh)) {
${$varname}[count($$varname)] = array_combine($header, $line);
}
fclose($fh);
}
foreach($MSFT_data as $val){
$MSFT[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$MSFT = json_encode($MSFT);
foreach($AAPL_data as $val){
$AAPL[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$AAPL = json_encode($AAPL);
foreach($FB_data as $val){
$FB[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$FB = json_encode($FB);
JS code:
$(function () {
var seriesOptions = [],
yAxisOptions = [],
colors = Highcharts.getOptions().colors;
seriesOptions[0] = {
name: 'MSFT',
data: <? php echo $MSFT; ?>
};
seriesOptions[1] = {
name: 'AAPL',
data: <? php echo $AAPL; ?>
};
seriesOptions[2] = {
name: 'FB',
data: <? php echo $FB; ?>
};
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
If you have any questions or need further information, please let me know with a comment.
Thanks
BTW: I have all necessary assets included for Highcharts to work; when I replace my JS + PHP with example code from the Highcharts site, it works beautifully. So the problem clearly lies in my JS + PHP code.
Alright, I believe I found the problem, it lies in the way that you are storing each individual point in the array.
Instead of this (which is passing a string x,y separated by a comma):
strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close'];
You are going to want to use something like this (Highcharts accepts arrays or associative arrays):
array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
That will store the X and Y variables as an array instead of comma separated string for the javascript to pass as data.

How to get the JSON working with PHP

I have the following code which pass data formatted as JSON to PHP through Ajax, but the PHP code doesn't print out the result.
var array_str_idnum = [];
for (var i=0;i<2;i++) {
array_str_idnum[i] = [];
}
$('#movetoset').click(function() {
if ($('#selectsett').val() === 'General') {
}
for(j=0;j< (array_str_idnum[0]).length;j++) {
if((document.getElementById('check' + array_str_idnum[0][j]).checked) && (array_str_idnum[1][j] != "moved")) {
document.getElementById('imagediv' + array_str_idnum[0][j]).style.display = 'none';
array_str_idnum[1][j] = "moved";
index = ((array_str_idnum[0]).length - 1 - j) + '';
var str = $("#complicated").serialize() + "&myindex=" + encodeURIComponent(index) ;
var desc_str = document.getElementById('textarea' + array_str_idnum[0][j]).value;
str = str + "&mydescription=" + encodeURIComponent(desc_str);
$.ajax({
type: "POST",
url: "addtoset.php",
data: str,
cache: false,
success: function(msg) {
$("#formstatus").ajaxComplete(function(){$(this).fadeIn("slow").html(msg + '<br /><br />')});
$("#formstatus").append(msg);
}
});
}
}
mydata = JSON.stringify(array_str_idnum);
$.ajax({
type: 'post',
cache: false,
url: 'parser.php',
data: {myJson: mydata},
success: function(msg) {
$("#formstatus").ajaxComplete(function() { $(this).fadeIn("slow").html(msg) });
}
});
});
Here is my PHP code:
$decoded = json_decode($_POST['myJson'],true);
// do something with data here
echo "decoded = $decoded[1][0]";
What's wrong with the code?
I think you want to fix your PHP code like others suggested, like so:
<?php
if ( !empty($_POST['myJson']) && strlen($_POST['myJson']) > 0 )
{
$decoded = json_decode( $_POST['myJson'], true );
// Echo out the JSON onject as a JavaScript variable.
echo "decoded = {$decoded[1][0]};";
}
else
{
// Echo out the JSON onject as a JavaScript variable.
echo "decoded = null;";
}
?>
Here is your JavaScript code with some minor suggestions:
<script type="text/javascript">
$( document ).ready(function()
{
var array_str_idnum = [];
// Init the array with two elemsnts that contain empty literal arrays.
for ( var i = 0; i < 2; i++ )
{
array_str_idnum[ i ] = [];
}
$( "#movetoset" ).click(function()
{
var $checkbox, str, desc_str, elementSuffix;
// I believe the code in here was removed for privacy reasons.
// I also believe it populats 'array_str_idnum' with some values of some kind.
if ( $("#selectsett").val() === "General" )
{
// ...
}
for ( var i = 0; i < (array_str_idnum[0]).length; i++ )
{
elementSuffix = array_str_idnum[ 0 ][ i ];
// Grab the checkbox.
$checkbox = $( "#check" + elementSuffix );
if ( $checkbox.checked && (array_str_idnum[1][i] != "moved") )
{
// Hide the image.
$( "#imagediv" + elementSuffix ).css({ "display": "none" });
// Indicate that this one is now moved, so do NOT process it again.
array_str_idnum[ 1 ][ i ] = "moved";
index = ( (array_str_idnum[0]).length - 1 - i ) + '';
// Setting str here will reinitialize it
str = $( "#complicated" ).serialize() + "&myindex=" + encodeURIComponent( index );
desc_str = $( "#textarea" + elementSuffix ).value;
str = str + "&mydescription=" + encodeURIComponent( desc_str );
// Bad idea to put ajax call in a loop.
$.ajax({
"type": "POST",
"url": "addtoset.php",
"data": str,
"cache": false,
"success": function( msg )
{
$( "#formstatus" ).ajaxComplete(function()
{
$( this ).fadeIn( "slow" ).html( msg + "<br /><br />" );
});
$( "#formstatus" ).append( msg );
}
});
}
}
mydata = JSON.stringify( array_str_idnum );
$.ajax({
"type": "POST",
"cache": false,
"url": "parser.php",
"data": { myJson: mydata },
"success": function( msg )
{
$( "#formstatus" ).ajaxComplete(function()
{
$( this ).fadeIn( "slow" ).html( msg )
});
}
});
});
});
</script>
Maybe your only problem is the echo statement. You'll have to change that to
echo "decoded = ".$decoded[1][0];
or
echo "decoded = {$decoded[1][0]}"; //
This is because PHP only notices "normal" variables in double-quoted strings. For array elements (or object properties) you'll have to use curly braces around the variable or use string concatenation.

Categories