jQuery Flot with PHP - php

I was dealing today with Flot and when I try to get the data from PHP (with json_encode()) I can't get it work properly.
I could display labels but no chart is created.
PHP
$newData = array();
$newData[0] = array();
$newData[1] = array();
$newData[2] = array();
$newData[0]['label'] = 'Slice 1';
$newData[1]['label'] = 'Slice 2';
$newData[2]['label'] = 'Slice 3';
$newData[0]['color'] = '#122b45';
$newData[1]['color'] = '#064792';
$newData[2]['color'] = '#9e253b';
$newData[0]['data'] = array();
$newData[0]['data'][0] = 1;
$newData[0]['data'][1] = 1000;
$newData[1]['data'] = array();
$newData[1]['data'][0] = 1;
$newData[1]['data'][1] = 500;
$newData[2]['data'] = array();
$newData[2]['data'][0] = 1;
$newData[2]['data'][1] = 100;
echo json_encode($newData);
jQuery
$.ajax({
url: "get-stats.php",
type: "POST",
async: false,
dataType : 'JSON',
data: {section: section, endDate: endDate, startDate: startDate},
success: function(data){
$.plot($("#flot"), data,{
series: {
pie: {
show: true
},
grid: {
hoverable: true,
clickable: true
}
}
}
});
Can anyone tell me where I'm doing wrong?
Labels and colors are ok but it seems I can't get the data.
Thank you for your time and concern in advance.

I found the problem and solution. I had to do following for the data;
$newData[0]['data'] = array(array(1,100));
This saved my day.

Related

My indices are defined but I still get the unidentified error

So I have this strip of code working for one page and not working for another page... Same code, same form name attributes, same php functionality on the server side. I'm calling with jquery ajax.. Calling from one page, it works completely fine... When I call from another page, it gives me "Unidentified index"
I've tried changing the names around (to remove duplicates and all)..
I seem to be sure that the names are correct though.
<script type="text/javascript">
$('#uploadcsv').submit(function(e){
e.preventDefault();
$.ajax({
url: "functions/grocerystore.php?item=fetchcontacts",
method: "post",
data: new FormData(this),
dataType: 'json',
contentType: false,
cache: false,
processData: false,
success: function(data){
console.log(data);
var accumulator = "";
var filetype = $('#uptype').val();
if(filetype == "csv"){
for(trav=0; trav<data.length; trav++){
accumulator += data[trav];
if(trav < data.length-1)
accumulator += "\r\n";
}
}else{
for(trav=0; trav<data.length; trav++){
accumulator += data[trav];
}
}
var mobilenumbers = $('#mobilenumbers');
mobilenumbers.html(accumulator);
},
error: function(data){
console.log(data);
}
});
});
</script>
php
case 'fetchcontacts':
if(!empty($_FILES['customFilex']['name'])){
$name = explode('.',$_FILES['customFilex']['name']);
$extension = end($name);
$file_data = fopen($_FILES['customFilex']['tmp_name'],"r");
if($extension == 'csv'){
fgetcsv($file_data);
$mobile = array();
$init = 0;
while($row = fgetcsv($file_data)){
$mobile[$init] = $row[0];
$init++;
}
fclose($file_data);
}else{
if ($file_data = fopen($_FILES['customFilex']['tmp_name'], 'r')) {
$mobile = array();
$init = 0;
while (!feof($file_data)) {
$row = fgets($file_data);
$mobile[$init] = $row;
$init++;
}
fclose($file_data);
}
}
echo json_encode($mobile);
}else{
$report["status"] = "failed";
echo json_encode($report);
}
break;
I just need it to accept my file...
You are using $_FILES['customFilex']['tmp_name']without checking if the keys exists in the $_FILES array.

Recover php mysql query with ajax/json?

How to recover data from research by json? I would like to recover the separate items as the result show in php page to create new elements, for example recover item.f, item.m to create new elements like item.f < / div> < span > item.m. .. thank you
(error presented at)
Error Can not read property of items " of null
Php page ( does the query )
if ($_GET['action'] == "chatheartbeat") { chatHeartbeat(); }
function chatHeartbeat() {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$items = '';
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$items. = << < EOD
{
"s": "0",
"f": "{$chat['de']}",
"m": "{$chat['mensagem']}",
"i": "{$chat['img']}"
},
EOD;
}
}
Index ( calls the pair query present the results - error here - need help here)
$.ajax({
url: "asd.php?action=chatheartbeat",
cache: false,
dataType: "json",
success: function(data) {
$.each(data.items, function(i, item) {
alert(item.f)
});
}
});
As #jeroen says dont manually generate JSON Strings use json_encode() to create a JSONString from a PHP array or an object.
if ($_GET['action'] == "chatheartbeat") {
$sql = "select * from mensagens ";
$query = mysql_query($sql);
$chatBoxes = array();
while ($chat = mysql_fetch_array($query)) {
$t - new stdClass();
$t->s = "0";
$t->f = $chat['de'];
$t->m = $chat['mensagem'];
$t->i = $chat['img'];
$chatBoxes[] = $t;
}
$items = json_encode($chatBoxes);
// now just echo $items to return it to the javascript in the browser
// here or later in the code if there is more to your code than you showed us
echo $items;
}
References:
json_encode()
json_decode()
Thank you all for the help, I managed to solve the problem as follows
Php page ( does the query )
$result = mysql_query("SELECT * FROM mensagens");
while( $array = mysql_fetch_assoc($result)){
$table[]= array("de"=>$array['de'],"mensagem"=>$array['mensagem']); }
echo json_encode($table);
Index
$.ajax({
url: 'asd.php',
dataType: 'json',
success: function(data)
{
for($i=0; $i < data.length; $i++){
$("#chatbox_"+chatboxtitle+" .chatboxcontent").append(
'<div class="message"><span class="from">'+data[$i].de+':
</span><span class=content">'+data[$i].mensagem+'</span></div>');
}}
});

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" }
]
}

AJAX cannot access an object data value passed from php

I have a php.php file to receive data then pass the result back to AJAX, like this:
<?php
$p1 = $_POST["p1"];
$c1 = $_POST["c1"];
$resultx['r1'] = "XXX";
$resultx['r2'] = 0;
$resultx['r3'] = 100;
$resultx['r4'] = 1000;
echo json_encode($resultx);
And in my js file I have:
$.ajax({
url: 'php.php',
type: 'POST',
data: {
p1: 5,
c1: 100
},
cache: false,
success: function (resultx) {
var result = resultx;
console.log(result);
var my1 = document.getElementById('my1');
var my2 = document.getElementById('my2');
var my3 = document.getElementById('my3');
var my4 = document.getElementById('my4');
my1.textContent = "Id : "+result.r1;
my2.textContent = "Rank : "+result.r2;
my3.textContent = "Total players : "+result.r3;
my4.textContent = "Top credit : "+result.r4;
},
});
The my1 my2 my3 my4 fields all print with undefined even though the console log show the value of:
{"r1":"XXX","r2":0, "r3":100, "r4":1000}
When I change the statement
var result = resultx;
to
var result = JSON.parse(resultx)
the javascript console prints a error message of uncaught syntax error unexpected token.
Please help!

Sending array from PHP to javascript through ajax

I have this php code to return many arrays to javascript through ajax.
<?php
ini_set('display_errors', 1);
error_reporting(E_ALL);
function get_events_data() {
// load SimpleXML
$nodes = new SimpleXMLElement('my_events.xml', null, true);
$event_id = array();
$channel_id = array();
$channel_name = array();
$channel_onclick = array();
$event_site = array();
$event_url = array();
$start_date = array();
$start_time = array();
$end_date = array();
$end_time = array();
$event_notes = array();
$n = 0;
foreach($nodes as $node)
{
$event_id[$n] = $node['id'];
$channel_id[$n] = $node->channel['id'];
$channel_name[$n] = $node->channel->name;
$channel_onclick[$n] = $node->channel->onclick;
$event_site[$n] = $node->event_site->name;
$event_url[$n] = $node->event_site->url;
$start_date[$n] = $node->start_date;
$start_time[$n] = $node->start_time;
$end_date[$n] = $node->end_date;
$end_time[$n] = $node->end_time;
$event_notes[$n] = $node->notes;
$n++;
}
$return['event_id'] = $event_id;
$return['channel_id'] = $channel_id;
$return['channel_name'] = $channel_name;
$return['channel_onclick'] = $channel_onclick;
$return['event_site'] = $event_site;
$return['event_url'] = $event_url;
$return['start_date'] = $start_date;
$return['start_time'] = $start_time;
$return['end_date'] = $end_date;
$return['end_time'] = $end_time;
$return['event_notes'] = $event_notes;
echo json_encode($return);
}
echo get_events_data();
?>
On the javascript side I have this code to access the arrays.
$.ajax({
url: "get_events_data.php",
type: "POST",
dataType : 'json',
data: { },
cache: false,
async: false,
success: function (rdata) {
var alert_data = 'event_id '+rdata.event_id[0]+'<br/>'+
'channel_id '+rdata.channel_id[0]+'<br/>'+
'channel_name '+rdata.channel_name[0]+'<br/>'+
'channel_onclick '+rdata.channel_onclick[0]+'<br/>'+
'event_site '+rdata.event_site[0]+'<br/>'+
'event_url '+rdata.event_url[0]+'<br/>'+
'start_date '+rdata.start_date[0]+'<br/>'+
'start_time '+rdata.start_time[0]+'<br/>'+
'end_date '+rdata.end_date[0]+'<br/>'+
'end_time '+rdata.end_time[0]+'<br/>'+
'event_notes '+rdata.event_notes[0]+'<br/>';
alert (alert_data);
},
error: function (request, status, error) {
alert ("status "+status+" error "+error+"responseText "+request.responseText);
},
});
When I print out the first element of each array on the javascript side, it shows as "object" doesn't show the value in that array. What is the right way of accessing the array data on the javascript side?
In JavaScript, an associative array is pretty much an object. Your script is working correctly. Do a console.log() with your data and explore how it prints out in the console, then use that to access the data. You could also post up the JSON data in question and probably get more detailed answers.
The answer to this question showed me how to do this. Reading a json encoded array in javascript
The json encoded rdata object returned from the PHP function could be read like this rdata.event_id[i]["0"]. Here is sample code for the objects within rdata.
var event = rdata.event_id[i]["0"]+' '+
rdata.channel_name[i]["0"]+' '+
rdata.channel_onclick[i]["0"]+' '+
rdata.event_site[i]["0"]+' '+
rdata.event_url[i]["0"]+' '+
rdata.event_onclick[i]["0"]+' '+
rdata.start_date[i]["0"]+' '+
rdata.start_time[i]["0"]+' '+
rdata.end_date[i]["0"]+' '+
rdata.end_time[i]["0"]+' '+
rdata.event_notes[i]["0"]+' ';
$('#event_list').append(event);
Use this instead of your 'similar' code:
foreach($nodes as $node)
{
$event_id[] = $node['id'];
$channel_id[] = $node->channel['id'];
$channel_name[] = $node->channel->name;
$channel_onclick[] = $node->channel->onclick;
$event_site[] = $node->event_site->name;
$event_url[] = $node->event_site->url;
$start_date[] = $node->start_date;
$start_time[] = $node->start_time;
$end_date[] = $node->end_date;
$end_time[] = $node->end_time;
$event_notes[] = $node->notes;
}
you need to either echo
echo json_encode($return);
or
echo get_events_data();
better:
echo json_encode($return);
} // end of function
then next line
get_events_data();

Categories