I am trying to display a JSON object query from a database, the JSON object I receive seems to be correct:
{
"cols": [
{
"id": "A",
"label": "Date",
"type": "string"
},
{
"id": "B",
"label": "User",
"type": "string"
},
{
"id": "C",
"label": "Cement Brand",
"type": "string"
},
{
"id": "D",
"label": "Volume",
"type": "string"
},
{
"id": "E",
"label": "Type",
"type": "string"
}
],
"rows": [
{
"c": [
{
"v": "08-06-2013"
},
{
"v": "razee.hj#gmail.com"
},
{
"v": "Muthana"
},
{
"v": "27"
},
{
"v": "Local Plant"
}
]
}
]
}
but there seems to be a problem with the php file I query data from but I can't find the mistake.
This is the dataTableViewDaily.php file
<?php
$selectQuery = 'SELECT * FROM competitive_daily_volume';
$table = array();
$table['cols'] = array(
array("id"=>"A","label"=>"Date","type"=>"string"),
array("id"=>"B","label"=>"User","type"=>"string"),
array("id"=>"C","label"=>"Cement Brand","type"=>"string"),
array("id"=>"D","label"=>"Volume","type"=>"string"),
array("id"=>"E","label"=>"Type","type"=>"string")
);
$rows = array();
$result = mysql_query($selectQuery);
while($row = mysql_fetch_assoc($result)){
$temp = array();
$temp[] = array("v"=> $row['Date']);
$temp[] = array("v"=> $row['UserId']);
$temp[] = array("v"=> $row['CementBrand']);
$temp[] = array("v"=> $row['VolumeBGLP']);
$temp[] = array("v"=> $row['Type']);
$rows[] = array("c"=> $temp);
}
$table['rows'] = $rows;
$jsonObj = json_encode($table);
header('Cache-Control: no-cache, must-revalidate');
header('Content-type: application/json');
echo $jsonObj;
?>
And this is the javascript file:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['table']});
</script>
<script type="text/javascript">
function drawVisualization() {
// var jsonData = null;
var jsonData = $.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, null);
}
google.setOnLoadCallback(drawVisualization);
</script>
</head>
<body style="font-family: Arial;border: 0 none;">
<div id="table"></div>
</body>
</html>
I have been working on this for quiet long time and I can't find what I am missing, would appreciate any kind of comments.
The problem is this:
var jsonData = $.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false
}).responseText;
Change it to:
var jsonData;
$.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false,
success:function(data){
//get data in your callback
jsonData = data;
}
});
Or use a recommended approach with promise and avoiding async: false:
$.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
}).done(function(jsonData){
var data = new google.visualization.DataTable(jsonData);
// Create and draw the visualization.
visualization = new google.visualization.Table(document.getElementById('table'));
visualization.draw(data, null);
});
Need to change this
var jsonData = $.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false
}).responseText;
var data = new google.visualization.DataTable(jsonData);
to this
$.ajax({
url: "php/DailyVolume/dataTableViewDaily.php", // make this url point to the data file
dataType: "json",
async: false,
success : function(response){
var data = new google.visualization.DataTable(response);
// other code
}
});
Related
I tried to make dropdown search.. how do I make a datatable with ajax response in the form of html if I use codeigniter?
I have tried the console to display the html in response ajax and it works but the response data cannot run on the datatable..
this is my ajax and php code
$(document).ready(function(){
$('#example').DataTable();
$("#periode1").on('change', function(){
var value = $(this).val();
$.ajax({
url: '<?= base_url('Kriteria/getPost') ?>',
type: 'POST',
data: 'request='+value,
success:function(data)
{
console.log(data);
$("#tampil_kriteria").html(data);
$('#example').DataTable();
}
});
});
});
.
public function getPost()
{
$data['title'] = 'Manajemen Data';
$data['title2'] = 'Daftar Kriteria';
$data['user'] = $this->Kriteria_model->getUserById();
$data['periode'] = $this->Kriteria_model->getAllPeriode();
$this->load->view('templates/header', $data);
$this->load->view('templates/menu', $data);
$id = $this->input->post('request');
if($id){
$data['kriteria2'] = $this->Kriteria_model->getAllKriteria($id);
$this->load->view('kriteria/tampil_kriteria', $data);
} else {
$id = $this->Kriteria_model->getId();
$data['kriteria'] = $this->Kriteria_model->getAllKriteria($id);
$this->load->view('kriteria/index', $data);
}
$this->load->view('templates/footer');
}
A possible solution could be:
encode the result of your php script in JSON format as:
{
"data": [
{
"title": "Manajemen Data",
"title2": "Satou",
"user": "Accountant",
"periode": "Tokyo",
......
},
{
"title" : "myTitle2",
..........
}
]
}
Change your Jquery function as:
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": {
"url": "myPhpScript.php",
"type": "POST"
},
"columns": [
{ "data": "title" },
{ "data": "title2" },
{ "data": "user" },
{ "data": "periode" },
..........
]
} );
where title, title2, user, periode, ... are the name of the columns in HTML code
I am having trouble sending $_POST data via jQuery Ajax. I have read over everything I can find regarding the matter and still I am getting nowhere. I have even gone back to very basic data and still nothing, the JSON data has been validated using the JSON validate site. For the life of me I cannot echo/print_r/var_dump or get access to any data.
My JavaScript:
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(){
alert("success");
console.log(content);
window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
});
My PHP:
<?php
if(isset($_POST['data'])) {
$json = stripslashes($_POST['data']);
var_dump(json_decode($json, true));
} else {
echo "No Data";
}
?>
So I do get the alert("success"), and then get redirected to test.php
once at test.php I get the echo "No Data".
Thanks in advance for any help with this issue.
The reason is you are using window.location to redirect to the PHP file (without any post data) instead of posting the form on test.php.
You should either post the form without ajax on test.php.
Or use the response from test.php in your success function.
$('#updateJSON').click(function(){
var content = [{
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
}];
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: content},
cache: false,
success: function(response){
alert("success");
console.log(response);
//window.location = "test.php";
},
error:function(){
alert('ajax failed');
}
});
You are passing data as a string to ajax file. Please use JSON.stringify(conten) to pass data as a json format in ajax file.
use
data: {data: JSON.stringify(content)}
in place of
data: {data: content}
Use:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
Then access each field as follows:
$field1 = #$request->field1Name;
$field2 = #$request->field2Name;
etc..
EDIT:
Well, the first part of the answer is still valid.
I've tried your code and slightly modified it on my machine, and i was able to access the whole data as you will see below:
Javascript: removed the square brackets from the outside of your JSON and removed the curly brackets from the 'data' part of the ajax since they are not necessary
as you can see, i've also added the "data" to the success function so i can debug the response from test.php better
$(document).ready(function(){
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
var someText = "someText";
$.ajax({
type: 'POST',
url: 'test.php',
data: JSON.stringify(content),
cache: false,
success: function(data){
alert(data);
console.log(content);
},
error:function(){
alert('ajax failed');
}
});
});
});
PHP:
<?php
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$field1 = #$request->id;
echo $field1;
and $field1 is echoed as "21", the correct answer
You can apply this to your code and check also.
Thanks everyone for the help I have managed to figure it out with the help of each of you.
I needed to create in the test.php file a, $json = array(), and then populate the array, $json[] = json_decode($_POST['data']);
that then allowed me to place the contents in a JSON file.
here is the php code:
<?php
$json = array();
if($_POST['data']) {
$json[] = json_decode($_POST['data']);
file_put_contents("../JSON/test.json",json_encode($json));
} else {
echo "No Data";
}
?>
and as long as the file "JSON/test.json" exists then it will write the JSON passed from the JS.
I would like to note:
without the JSON.stringify(content); the data is NULL so thank you # Rahul Patel for making sure this was being applied.
the JSON data is valide according to the JSON validate site.
also just for keeps sake the JS code:
$('#updateJSON').click(function(){
var content = {
"id": 21,
"children": [{
"id": 196
}, {
"id": 195
}, {
"id": 49
}, {
"id": 194
}]
};
$.ajax({
type: 'POST',
url: 'test.php',
data: {data: JSON.stringify(content)},
cache: false,
success: function(){
alert("JSON Updated");
},
error:function(){
alert('ajax failed');
}
});
});
How do I load json data with serverside processing in a dataTable?
I'm trying to build a custom Wordpress plugin and display results from wpdb inside a dataTable.
I get a successful AJAX return call, but the dataTable only shows a "Processing..." stage and the table does not fill the rows (keeps empty).
Although I have read many(!) similar problems and answers here, any help to load data with ajax and json_encode is much appreciated.
The current code:
dahsboard.php
<table id="table-id" cellpadding="1" cellspacing="1" width="100%">
<thead><tr>
<th>h_id</th>
<th>h_subject</th>
</tr></thead>
ajax-grid-data.php
add_action('wp_ajax_my_action', 'my_action_callback');
function my_action_callback(){
global $wpdb;
$query = "SELECT h_id, h_subject FROM wp_tablename ORDER BY h_id limit 3";
$myrows = $wpdb->get_results($query);
foreach ($myrows as $value) {
$ResultData['h_id'] = $value->h_id;
$ResultData['h_subject'] = $value->h_subject;
$data[] = $ResultData;
}
$json_data = array(
"draw" => 1,
"recordsTotal" => 3,
"recordsFiltered" => 3,
"data" => $data,
);
echo json_encode($json_data);
die();
}
I think that the problem is in datatype formatting underneath:
dashbboard.js
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataSrc:'',
dataType : "json",
contentType: "application/json; charset=utf-8",
//dataSrc: function(data){ return data.data; },
//async : false,
//processData: true,
//accepts: {json: "application/json, text/javascript"},
success: function(data){
console.log(JSON.stringify(data)); // successful echo data objects are shown in dashboard.
},
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});
Current results
Result php file test: .../wp-admin/admin-ajax.php?action=my_action
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result ajax success function, console data:
{"draw":1,"recordsTotal":3,"recordsFiltered":3,"data":[{"h_id":"37168","h_subject":"6216"},{"h_id":"37169","h_subject":"7021"},{"h_id":"37170","h_subject":"8923"}]}
Result dashboard table only shows: processing...
Deleting the dataSrc and success function did wonders and fills up the dataTable with data. I really appreciate the help and efforts of #bassxzero and #davidkonrad.
Ensuring that there is an answer, "on behalf of" the new version of dashboard.js:
var oTable;
jQuery(document).ready(function() {
jQuery.fn.dataTable.ext.errMode = 'throw';
oTable = jQuery('#table-id').DataTable( {
"serverSide": true,
"processing": true,
"columnDefs": [{"defaultContent": "-","targets": "_all"}],
"columns": [
{ "data": "h_id" } ,
{ "data": "h_subject" }
],
"ajax":{
url: "admin-ajax.php?action=my_action",
type: "post",
dataType : "json",
contentType: "application/json; charset=utf-8",
error: function(){
jQuery("#tablename").append('<tbody class="grid-error"><tr><th colspan="2">No results.</th></tr></tbody>');
jQuery("#tablename_processing").css("display","none");
}
},
});
});
I wish to extract one variable by one variable from my json file. My goal is to use this variable in php, to be able to do mysql query for exemple.
So my json file is here: pages/getRank-classic.php?idstart=0
[
{"rank":1,"id":"111","site_name":"test1","site_vip":"No","boost":"0","site_banner":"test.png","site_banner_wallrank":"","site_pointstotaux":"5044","site_motclef1":"Pvp\/Fac","site_motclef2":"Skyblock","site_motclef3":"Cr\u00e9atif","site_motclef4":"Hunger-Games","site_motclef5":"SKywars\/Mini-Gam","site_presentationvideo":"3TGjebmNOfs"},
{"rank":2,"id":"222","site_name":"test2","site_vip":"No","boost":"0","site_banner":"test.jpg","site_banner_wallrank":"","site_pointstotaux":"4114","site_motclef1":"hunger","site_motclef2":"games","site_motclef3":"pvp","site_motclef4":"survival","site_motclef5":null,"site_presentationvideo":"3TGjebmNOfs"}
]
I am trying to use it in include like:
<script type="text/javascript" >
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
alert(test.id);
alert(test.rank);
}
});
</script>
So how I can do it please?
Since it is an array of json, you need to specify the index too.
test[0].id
Also you can iterate through the object using this way,
var data = [{
"rank": 1,
"id": "111",
"site_name": "test1",
"site_vip": "No",
"boost": "0",
"site_banner": "test.png",
"site_banner_wallrank": "",
"site_pointstotaux": "5044",
"site_motclef1": "Pvp/Fac",
"site_motclef2": "Skyblock",
"site_motclef3": "Cr\u00e9atif",
"site_motclef4": "Hunger-Games",
"site_motclef5": "SKywars/Mini-Gam",
"site_presentationvideo": "3TGjebmNOfs"
}, {
"rank": 2,
"id": "222",
"site_name": "test2",
"site_vip": "No",
"boost": "0",
"site_banner": "test.jpg",
"site_banner_wallrank": "",
"site_pointstotaux": "4114",
"site_motclef1": "hunger",
"site_motclef2": "games",
"site_motclef3": "pvp",
"site_motclef4": "survival",
"site_motclef5": null,
"site_presentationvideo": "3TGjebmNOfs"
}];
$(data).each(function () {
alert(this.id);
});
You can fetch the json using the ajax, then in the success event, put this code like,
$.ajax({
type: 'POST',
dataType: 'json',
url: '/pages/getRank-classic.php?idstart=0',
data: data,
cache: false,
success: function(test) {
$(test).each(function () {
alert(this.id);
});
}
});
I finally used php like that =>
<?php
$jsonlink = '/pages/getRank-classic.php?idstart=0';
$json = file_get_contents($jsonlink);
$link = mysql_connect('localhost', 'database', 'password');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('database', $link);
$result = json_decode($json);
foreach($result as $key => $value) {
if($value) {
mysql_query("UPDATE `database`.`sites` SET `site_rank` = '$value->rank' WHERE `sites`.`site_id` = '$value->id'");
}
mysql_close;
}
?>
JSON output: (from dt.php)
[{
"name":"Year",
"data":[2012,2013]
},{
"name":"A",
"date":[111,24]
},{
"name":"B",
"date":[34,0]
},{
"name":"C",
"date":[365,43]
},{
"name":"D",
"date":[496,0]
}]
Javascript:
$(document).ready(function() {
var chart;
var option = {
chart: {
renderTo: 'hcChart',
type: 'column'
},
title: {
text: 'Testing'
},
xAxis: {
categories: []
},
series: []
};
$.getJSON("dt.php", function(json) {
option.xAxis.categories = json[0]['data'];
option.series[0] = json[1];
option.series[1] = json[2];
option.series[2] = json[3];
option.series[3] = json[4];
chart = new Highcharts.Chart(option);
});
});
The chart does show out with the legends but the there are no single value showing up.. Any help?
Change date to data:
[{"name":"Year","data":[2012,2013]},{"name":"A","data":[111,24]},{"name":"B","data":[34,0]},{"name":"C","data":[365,43]},{"name":"D","data":[496,0]}]
Also remember to render the chart to a div id. option.chart.renderTo = 'myChart';
Working example:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
var chart;
var option = {
chart: {
renderTo: 'hcChart',
type: 'column'
},
title: {
text: 'Testing'
},
xAxis: {
categories: []
},
series: []
};
$.getJSON("dt.php", function (json) {
option.xAxis.categories = json[0]['data'];
console.log(json);
option.series[0] = json[1];
option.series[1] = json[2];
option.series[2] = json[3];
option.series[3] = json[4];
option.chart.renderTo = 'myChart';
chart = new Highcharts.Chart(option);
});
});
</script>
<div id="myChart"></div>