So i am using 2 apis of php that echo's value in json encode
one api contains all the data and the other api has the same data but only where one of the value is true
e.g
data from api contains 50 rows
data from api 2 contains 20 rows because that api shows same data but where a value is Yes
i cannot use join in tables as they are from different sources
so i was trying to join them using jQuery
with my code only the first value changes but not the rest
ive tried the following code but it will only change the first value
$.get("customapi.php", {
data: 'get_data'
}, function(response) {
$("#autovisit tbody").html("");
for (var i = 0; i < response.length; i++) {
html = "<tr>";
html += `
<td><b>${i+1}</b></td>
<td>${response[i]['name']}</td>
<td>${response[i]['p_name']}</td>
<td>${response[i]['p_type']}</td>
<td>${response[i]['a_date']}</td>
<td>${response[i]['l_date']}</td>
<td>${response[i]['r_date']}</td>
<td>${response[i]['d_name']}</td>
<td id="get_visit" class="text-center">NO</td>
<td id="get_invoice" class="text-center">NO</td>`;
$("#autovisit tbody").append(html);
$.get("customapi2.php", {
data: 'get_data'
}, function(result) {
for (var i = 0; i < result.length; i++)
$("#get_visit").text(result[i]['VISITED']);
$("#get_invoice").text(result[i]['INVOICED']);
}, 'JSON');
}
}, 'JSON');
in the above api both have the same data in the following values
{response[i]['name']}
{response[i]['p_name']}
{response[i]['p_type']}
{response[i]['a_date']}
{response[i]['l_date']}
{response[i]['r_date']}
{response[i]['d_name']}
the rest two
that is visit and invoice is comming from the other api and i need to change that text but with this code when the first name is true it only changes that not the others
You can use the following code to update your column values.
What you will be doing here is assigning a specific id to a data cell and then using that id to update data cell based on values from second api call.
This is done assuming that name is unique in response
$.get(
"customapi.php",
{
data: "get_data"
},
function(response) {
$("#autovisit tbody").html("");
for (var i = 0; i < response.length; i++) {
html = "<tr>";
html += `
<td><b>${i + 1}</b></td>
<td>${response[i]["name"]}</td>
<td>${response[i]["p_name"]}</td>
<td>${response[i]["p_type"]}</td>
<td>${response[i]["a_date"]}</td>
<td>${response[i]["l_date"]}</td>
<td>${response[i]["r_date"]}</td>
<td>${response[i]["d_name"]}</td>
<td id="visit-`${response[i]['name']}`" class="text-center">NO</td>
<td id="invoice-`${response[i]['name']}`" class="text-center">NO</td>`;
$("#autovisit tbody").append(html);
}
$.get(
"customapi2.php",
{
data: "get_data"
},
function(result) {
for (var i = 0; i < result.length; i++)
$("#visit-`${result[i]['name']}`").text(result[i]["VISITED"]);
$("#invoice-`${result[i]['name']}`").text(result[i]["INVOICED"]);
},
"JSON"
);
},
"JSON"
);
Please not that your 2nd API call should be outside the for loop, otherwise it will have too many unnecessary requests
You need UNIQUE IDs!
There cannot be more than one get_visit and one get_invoice so change the ID of the cells to some unique you also can know in the second code
An actual ID is best, so change the uniqueID combo below to an database ID if you have it
var uniqueID;
for (var i = 0; i < response.length; i++) {
uniqueID = response[i]['name'] + "_" + response[i]['p_name']; // or whatever is unique
html = "<tr>";
html += `
<td><b>${i+1}</b></td>
<td>${response[i]['name']}</td>
<td>${response[i]['p_name']}</td>
<td>${response[i]['p_type']}</td>
<td>${response[i]['a_date']}</td>
<td>${response[i]['l_date']}</td>
<td>${response[i]['r_date']}</td>
<td>${response[i]['d_name']}</td>
<td id="${uniqueID}_visit" class="text-center">NO</td>
<td id="${uniqueID}_invoice" class="text-center">NO</td>`;
}
html += "</tr>";
...
for (var i = 0; i < result.length; i++)
uniqueID = result[i]['name'] + "_" + result[i]['p_name']; // or whatever is unique from above
$(`#${uniqueID}_visit`).text(result[i]['VISITED']);
$(`#${uniqueID}_invoice`).text(result[i]['INVOICED']);
}
I have used a datatable in my codeigniter application to dynamically print database values. I am trying to sum up all the columns including numeric and string values. The numeric values are correct but the string column sum is weirdly wrong. The sum only works for some of the values of the column. For example it sums up 8 out of 10 rows. But the numeric sum shows sum of all 10 rows.
I am providing the code below.
Note: I am trying to use the headercallback() to print the sums of the columns. I have used two headers for this.
Datatable HTML code:
<table id="tabular" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>Company</th>
<th>Status</th>
<th>Created Date</th>
<th>Total Contacts</th>
<th>Total Versions</th>
<th>Articles Assigned</th>
</tr>
</thead>
<thead id="totals">
<tr>
<th id="name">asdfasf</th>
<th></th>
<th></th>
<th id="contact"></th>
<th id="version"></th>
<th id="article"></th>
</tr>
</thead>
<tbody>......(Rest of the code)
JS code to initialize the datatable on the given HTML
$(document).ready(function() {
var oTable = $('#tabular').DataTable({
// "stateSave": true,
// "order": [],
"dom": '<"row search-padding" <"col-md-12 search-padding" <"col-md-6 search-padding pull-left" <"#inp">> <"col-md-6 search-padding" <"datatable-n pull-right" l >> > >rt <"row" <"col-md-6" i > <"col-md-6" p > >',
"columns" : [
{"width": "25%" },
{"width": "18.7%" },
{"width": "18.7%" },
{"width": "14%" },
{"width": "10.7%" },
{"width": "18.7%" },
],
"stashSave":true,
"order": [],
"processing": true,
"searching" : true,
"orderCellsTop": true,
"language": {
"emptyTable": "No companies found for the selected range."
},
//code to sum up columns...
"headerCallback": function () {
var api = this.api(),
columns = [0,3,4,5]; // Add columns here
for (var i = 0; i < columns.length; i++) {
$('#totals th').eq(columns[i]).html('Total: ' + api.column(columns[i], {filter: 'applied'}).data().sum() + '<br>');
}
}
} );
I have used the sum() api :
jQuery.fn.dataTable.Api.register( 'sum()', function ( ) {
return this.flatten().reduce( function ( a, b ) {
if ( typeof a === 'string' ) {
a = a.replace(/[^\d.-]/g, '') * 1;
}
if ( typeof b === 'string' ) {
b = b.replace(/[^\d.-]/g, '') * 1;
}
return a + b;
}, 0 );
} );
I have tried all the ways to get correct value. I have cross checked the database queries and I am getting the right data.
Hope I have made it clear. Suggestions would be helpful. Thanks
I have a table as the following datatable table :
<button id="addRow">Add New Row</button><br>
<table class="table table-striped table-bordered table-hover " id="example" cellSpacing=0 width="100%">
<thead>
<tr>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
</tr>
</thead>
<tr style="text-align: center;">
<td>hola</td>
<td>ciao</td>
<td>bonjour</td>
<td>yo</td>
<td>salut</td>
</tr>
</table>
I'd like to append elements using a javascript script as the following :
<script type="text/javascript">
$(document).ready(function () {
debugger;
var t = $('#example').DataTable({ "searching": true, "paging": true });
var counter = 1;
$('#addRow').on('click', function ciicici() {
var now = new Date();
var now = now.toMysqlFormat();
var tii = new Date();
tii.setSeconds(tii.getSeconds() - 50000);
var tii = tii.toMysqlFormat();
$.post( "sqlmachine_test_ajax.php", { timing: now,seconding: tii })
.done(function( data ) {
t.row.add([
counter +'.1',
counter +'.2',
counter +'.3',
counter +'.4',
counter +'.5'
]).draw();
counter++;
// });
//setTimeout(function(){ciicici();}, 5000);
}); // Automatically add a first row of data
$('#addRow').click();
});
</script>
The two are working properly, the only thins is that I'd like to retreive the elements to append trough an Jquery AJAX script.
Let's say I have a php page sending back 5 values I'd like to add to each column (instead of the counter1, counter2 etc...) as the following :
<?php
echo 'counter1, counter2, counter3, counter4, counter5';
?>
and in the javascript I wanted to put simply :
...
.done(function( data ) {
t.row.add([
data //(instead of the counters)
]).draw();
counter++;
...
I have tried this, as well as arrays and json encoded arrays, but all I get is the 5 results in the same first cell of the table.
So how could I append the ajax php response to a table as data in different cells of the table?
marko
When you get your data back from the call, you have to separate using .split().
so you can do this when you get your callback
.done(function( data ) {
var splitData = data.split(", ") //Split your data with the comma and space
$.each(splitData, function(e){ //For each piece of data
//Add your rows here one by one
t.row.add([
splitData[e] //Make sure the 'e' in the function and here are the same
]).draw();
})
counter++;
});
This a loose answer, I'll try to add more soon.
Edit: More info
what I normally do is echo everything with separators. So, in your case, I would echo 1, 2, 3, 4, 5:A, B, C, D, E. So when the data returns, that's what you'll see.
In your data success, you would do something like
var dataParts = data.split(":") //This splits your data into the 2 parts using the : separator
var dataPart1 = dataParts[0] //This will get 1, 2, 3, 4, 5
var dataPart2 = dataParts[1] //this will get A, B, C, D, E
Then from there, you split using commas.
var dataPieces1 = dataPart1.split(', ');
var dataPieces2 = dataPart2.split(', ');
Then run the loops. (using javascript's for loop is usually better than using jQuery's .each())
for(var i = 0; i < dataPieces1.length; i++){ //Start your for loop on the first part
//Create a row here using dataPieces1[i], this will loop and make a new
//row every time the next loop finishes
for(var j = 0; j < dataPieces2.length; j++){ //Start the second loop
//Not sure how you would want to do this, but here's some example code
//Since you're inside a row now, append your dataPieces2[j] to that row
//This will loop for every dataPieces2 and append each one as a column
//in that single row.
}
}
I am using PHP and MySQL to get total amount of orders made on each day during a selected time period and then save them in a *.csv file using PHP. I generate the chart from csv file and everything is ok but I would need to include days with no orders made as well. *.csv file content is something like that:
1,05-01
1,05-02
2,05-04
1,05-06
So on the chart they appear as 1 order made on 1st of May, 1 order made on 2nd of May and then 3rd of May is skipped- I need to show it on the chart with value 0. Can it be done with jQuery/highcharts (I don't have much experience with javascript) or should I edit the PHP to create file with those values, like this:
1,05-01
1,05-02
0,05-03
2,05-04
0,05-05
1,05-06
I use the following PHP code to save the file:
$result = mysqli_query($con,"$query");
$fp = fopen('data/temp.csv', 'w');
if ($fp && $result) {
while ($row = $result->fetch_array(MYSQLI_NUM)) {
fputcsv($fp, array_values($row));
}
}
And the following script to generate the chart:
var myCategories = [];
var myData = [];
var myChart;
$(document).ready(function() {
var options = {
chart: {
renderTo: 'chart-container',
defaultSeriesType: 'column'
},
title: {
text: 'Orders received in selected days'
},
xAxis: {
title: {text: 'Date'},
categories: []
},
yAxis: {
title: {
text: 'Orders'
}
},
series: []
};
$.get('data/temp.csv', function(data) {
var lines = data.split('\n').slice(0, -1); //generated csv file has \n after last entry so there is always an empty line I have to delete
$.each(lines, function(lineNo, line) {
var items = line.split(',');
myCategories.push(items[1]);
myData.push(parseInt(items[0]));
});
options.xAxis.categories = myCategories;
options.series = [{ data: myData }];
myChart = new Highcharts.Chart(options);
});
});
Only solution I found was to create some crazy query on MySQL side (I preffer to handle that logic in PHP) it seems this cannot be done with HighCharts, so in the end I modified my PHP code a little bit to add some extra loops. If someone is interested it now looks like this:
$result2 = mysqli_query($con,"$query2");
$fp = fopen('data/temp.csv', 'w');
$dayCompare=date("n-d", strtotime($theDay)); //I know which day is the first one selected so I save it as variable #theDay
while ($row = mysqli_fetch_array($result2)) {
if ($row['Date'] !== $dayCompare){
while ($row['Date'] !== $dayCompare){ //This "while" keeps on looping till the date from database matches the day
fputcsv($fp, array('0,'.$dayCompare));
$theDay= date("Y/m/d", strtotime($theDay . "+1 day"));
$dayCompare=date("n-d", strtotime($theDay));
}
} //Rest of the code is to be executed when dates match
fputcsv($fp, array($row['Orders'].",".$row['Date']));
$theDay= date("Y/m/d", strtotime($theDay . "+1 day"));
$dayCompare=date("n-d", strtotime($theDay));
}
for ($theDay; $theDay <= $lastDay; strtotime($theDay . "+1 day")) { //I added a "for" loop to fill in the empty days if the day of last order is earlier than the last day selected/current day.
fputcsv($fp, array('0,'.$dayCompare));
$theDay= date("Y/m/d", strtotime($theDay . "+1 day"));
$dayCompare=date("n-d", strtotime($theDay));
}
This produces sample output:
"1,5-01"
"1,5-02"
"0,5-03"
"2,5-04"
"0,5-05"
"1,5-06"
The only problem that it gives me now the data is saved in the *.csv file with quotes, but I solved it by modifying the *.js file with my script changing this part:
$.each(lines, function(lineNo, line) {
var items = line.split(',');
myCategories.push(items[1]);
myData.push(parseInt(items[0]));
});
To this:
$.each(lines, function(lineNo, line) {
var items = line.split(',');
myCategories.push(items[1].replace(/"/g,""));
myData.push(parseInt(items[0].replace(/"/g,"")));
});
Thanks to trimming the quote marks the output is as expected. Variables with dates are still quite elaborated but it seems it has to be like that since PHP has problems recognizing short dates when it is about doing math equations, and I also hope to modify that triple loop someday but this will have to wait at least till next deployment.
In the end I added one more loop to loop through the empty days when the last day selected is later than the day of last order, for example if 9th of May was selected and last order was on 7th there will be 2 lines added with 0 values for 8th and 9th.
I cannot get Highcharts to graph a scatter plot of 2 series. Actually, the graph isn't even showing up. Please help me determine what I'm doing wrong. I cannot find a scatter plot example to go off of and I am very new to this. I've got json data from a php file that looks like:
[[65,44],[66,37],[67,42],[68,55],[65,50],[65,41],[65,41],[68,41],[69,42],[70,47],[69,55],[67,45],[67,49],[67,53],[67,49],[68,51],[68,55],[68,57],[70,53],[69,66],[68,54],[69,52],[68,48]][[75,36],[72,42],[75,44],[69,56],[72,40],[73,37],[77,34],[77,40],[74,50],[77,45],[77,43],[75,47],[73,52],[73,50],[75,44],[72,54],[71,57],[72,57],[74,55],[74,54],[75,47],[78,45],[75,43]]
This should be two series in an (x,y) format. I want to graph these on a scatter plot in HighCharts. My HighCharts code is:
<script type="text/javascript">
$(function () {
var chart;
$(document).ready(function() {
$.getJSON("comfortgb1b.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container4',
type: 'scatter',
marginRight: 175,
marginBottom: 50
},
title: {
text: 'Comfort Level',
x: -20 //center
},
subtitle: {
text: '',
x: -20
},
xAxis: {
title: {
enabled: true,
text: 'Temp (F)'
},
min: 60,
max: 85,
startOnTick: true,
endOnTick: true,
showLastLabel: true
},
yAxis: {
title: {
text: 'Humidity (%RH)'
},
min: 30,
max: 100
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: '{point.x} F, {point.y} %RH'
}
},
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
});
});
});
</script>
Thanks in advance!
The php file that is creating the json data is below. How would I separate these arrays with a comma?
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode($ret1, JSON_NUMERIC_CHECK);
echo json_encode($ret2, JSON_NUMERIC_CHECK);
Not sure about this, but at first glance I think the array returned from the php file requires an additional square bracket outside it in order to be parsed as proper json. Currently it is:
[[65,44],[66,37]..][[75,36],[72,42]..]
From what I know, this is just two arrays. What you want is to enclose these arrays within an array. Try changing this to:
[[[65,44],[66,37]..],[[75,36],[72,42]..]]
That is, add an extra square bracket outside and separate the two arrays using a comma.
In addition, here:
series: [{
name: 'Night',
data: json(1)
}, {
name: 'Night',
data: json(2)
});
json(1) and json(2) are interpreted as function calls. You should instead use:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Night',
data: json[1]
});
EDIT ---- Edited as per OP edits
Also as requested, in order to add the commas and proper formatting, the php file can be changed at the last two lines as follows:
echo "[".json_encode($ret1, JSON_NUMERIC_CHECK).",";
echo json_encode($ret2, JSON_NUMERIC_CHECK)."]";
You have several things giving you problems. See this fiddle: http://jsfiddle.net/nbwN9/1/
First, I don't think your json is in the proper format for a 2 series plot. You have two arrays of data just butted up to each other rather than in another array. The linked fiddle corrects that (and stuffs it into a var since the getJSON() call will fail within jsFiddle). Each point is an array of (x,y) coords. Each series.data is an array of points. Your json will need to be an array of series.data arrays. So we're looking at nested arrays 3 deep.
Second, you seem to have a malformed set of chart options. Most notable is that your series node (with name and data) is inside your plotOptions node when it should be outside of it. And that series node is not terminated properly.
Third, once you get your json data and your chart options formatted correctly, accessing the json array is done like so:
series: [{
name: 'Night',
data: json[0]
}, {
name: 'Day',
data: json[1]
}]
The array is 0-based (so the first record will be indexed with a 0, second record with a 1, etc) and is access using the brackets [] not parentheses ()
Sorry, I renamed one of your series to "Day" so I could see the difference in the chart.
As far as the PHP script... try this:
$result1 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) NOT BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret1 = array();
while($item = mysql_fetch_array($result1)) {
$avg_return1 = $item['avg_return'];
$avg_hum1 = $item['avg_hum'];
$ret1[] = array($avg_return1,$avg_hum1);
}
$result2 = mysql_query("SELECT round(AVG(d_internal_duct_return),0) AS 'avg_return', round(AVG(d_evap_pre_humidity),0) AS 'avg_hum' FROM pheom.pheom_gb WHERE timestamp between subdate(curdate(), interval 2 month) and curdate() AND HOUR(Timestamp) BETWEEN 9 AND 22 GROUP BY DAY(Timestamp) ORDER BY Timestamp");
$ret2 = array();
while($item = mysql_fetch_array($result2)) {
$avg_return2 = $item['avg_return'];
$avg_hum2 = $item['avg_hum'];
$ret2[] = array($avg_return2,$avg_hum2);
}
echo json_encode(array($ret1,$ret2), JSON_NUMERIC_CHECK);