Communicate between PHP and Javascript - php

I have a table in database that has 2 columns Name | Age, I display it in a HTML page.
I want to sort the table in HTML page based on a field when the user clicks on it.
I have a PHP function to do the sorting based on a field.
But after obtaining the rows in sorted order in PHP, I'm looking for ways by which I can update the HTML table without navigating away from the page.

You do not need to communicate between the client and server to do this, just sort the table on the client directly.
There is a jQuery plug-in for this that works quite well:
http://tablesorter.com/docs/

You can do sorting in javascript, without having to communicate with the server. For example, this code will sort a table based on the content of the Nth column:
function sortTable(table, column, skipHeader) {
// Stick each row into an array.
var rows = [];
for (var i = skipHeader ? 1 : 0; i < table.rows.length; i++) {
rows.push(table.rows[i]);
}
// Sort the array based on the innerText of the column'th cell in each row
rows.sort(function(a, b){
a = a.cells[column].innerText;
b = b.cells[column].innerText;
return a < b ? -1 : (b < a ? 1 : 0);
});
// Re-order the rows by removing/appending in the sort order
for (var i = 0; i < rows.length; i++) {
var row = rows[i];
var container = row.parentElement;
container.removeChild(row);
container.appendChild(row);
}
}
For example, to sort the first table in the document, on the first column, and skip the header row:
sortTable(document.getElementsByTagName('table')[0], 0, true);
Obviously you'll want to modify this to suit your own tastes, especially the sorting, but it's a lot simpler than having to post the data back to the server, which I think is what you're proposing.

Since others have covered the fact that client-side sorting would work just fine here, I'll just point you to the resource with which I've had the most sucess doing this kind of thing: Google Data Tables, part of their Visualization Library. Here are the deets on what you can do (spoiler: everything you want and more).

Here is a link to a javascript library to make your tables sortable using javascript instead of php. I've used it many times, it works great.
Javascript Sortable Tables by: Stuart Langridge

Related

multiple days of week selection from Javascript checkbox to PHP and SQL

Is there a quick and elegant way of selecting one or more day(s) of week from Javascript checkbox, move it to PHP and get queries from SQL accordingly after processing, which boxes are checked, in PHP side-e.g. if I checked monday and wednesday, extract (dow from timestamp) = 1 or extract(dow from timestamp) = 3 should be added to my query string on the PHP end-
I had implemented a quick and dirty solution in C++/Qt before -in this question of mine:
Day(s) of week selection from QT checkbox to Postgresql
Then got an answer showing the shortest way to do it- and now I wonder if a similar way of such a short way is possible in PHP.
If the checkboxes are given, there aren't too many ways to implement this. Actually it's always the same: Read the values of the selected checkboxes and use them to build the query string.
Example (could be done easier with e.g. jQuery of course...):
var checkboxes = document.getElementById("checkboxes").getElementsByTagName("input"),
query = [];
for (var i = 0, l = checkboxes.length; i < l; ++i) {
// Get value of each selected checkbox and build the query string
if (checkboxes[i].checked) {
query.push("extract(dow from timestamp) = ", checkboxes[i].value, " or ");
}
}
if (query.length > 0) {
// Remove last "or"
query = query.slice(0, -1);
}
// Join "string builder" array to get the final query string
query = query.join("");
console.log(query);
DEMO (JSFiddle)
I don't quite understand though why you want JavaScript to build the string; SQL runs server-side, so why not just sending the values to the server and create the query string there?

Maths using javascript and multiple html fields

I have a script that dynamically creates a table with a varying number of columns and rows based on a db query.
This is done twice, on two different db tables.
I have a row at the bottom of each table with an input whose value is the sum of the cells in the column above.
These inputs are named itotal$m (where $m is an incrementing number) for the first table and etotal$m for the second table. So what I end up with is a number of input fields with the names itotal1, itotal2 etc for the first row of totals and etotal1, etotal2 etc for the second row.
I want to perform some simple maths with these totals, subtracting etotal1 from itotal1, etotal2 from itotal2 and so on, then displaying the result in another input.
I would like to use javascript function attached to an onChange event so that the user can change the input box values and see the result.
Unfortunately, I have not managed to figure out how to do this. Any help would be appreciated!
Assuming :
the two tables to have id="iTable" and id="eTable",
all the column total fields to have class="colTotal",
the two tables to be congruous (ie. their columns are in the same order),
the target input elements to have class="diffValue", then :
jQuery:
$(function(){
var $iTableTotals = $("#iTable .colTotal");
var $eTableTotals = $("#eTable .colTotal");
var $diffValues = $(".diffValue");
$(".colTotal").on('change keyup', function() {
$iTableTotals.each(function(i){
var diff = Number($iTableTotals.eq(i).val()) - Number($eTableTotals.eq(i).val());
$diffValues.eq(i).val(diff);
});
});
$iTableTotals.eq(0).change();
});
See fiddle

group mysql results into two separate divs

I have a mysql query that retrieves all my topic results. I then have a pagination system where results are separated into pages and the query's limit #,# changes based on what page you are on.
What I want to do is put all those results into two separate div containers. I want 21 results on each page. The first 9 I will put in one div. The next 12 will go in the other. Does anyone know an efficient way to do this? Should I use two queries, or javascript, or another way? I am just looking for the best most efficient way to do this. Unfortunately the pagination system makes two queries difficult. Any suggestions highly appreciated.
$sql = "SELECT * FROM topics LIMIT ?,?";
$stmt2 = $conn->prepare($sql);
$result=$stmt2->execute(array(somenumber,somenumber2));
I don't see any reason why you can't do a single MySQL query and use JavaScript to sort the results. Understand that I don't understand here what your data is coming back looking like, so any example I provide will have to remain pretty agnostic in this regard.
I will, however, assert as an assumption that you have a JavaScript array of length 21 with some data that is the basis for your display.
Assuming that we're just talking about the first 9, and the last 12, the sorting code is as simple as:
// assume my_array is the array mentioned above
for (var i = 0; i < 9; i += 1) {
var html = code_to_transform_data_from_array(array[i]);
$('.div1').append($(html));
}
for (var i = 9; i < 21; i += 1) {
var html = code_to_transform_data_from_array_b(array[i]);
$('.div2').append($(html));
}
If your sorting condition is any more complicated, then you'd be better off with something like...
while (my_array.length > 0) {
var item = my_array.pop();
if (sorting_condition) {
$('.div1').append(f1(item));
}
else {
$('.div2').append(f2(item));
}
}
(In the second example, I became a lazy typist and assumed f1 and f2 to be complete transformation functions. sorting_condition is your criteria for determining in which bucket something goes.
Hope that sets you off on the right track.

Real time graphing with flot, mysql, php

I'm trying to draw a real time graph as my mysql table is constantly being inserted with values, like a moving graph referenced from
http://kalanir.blogspot.com/2009/11/how-to-plot-moving-graphs-using-flot.html
The values actually come from a carbon dioxide sensor which updates the value of the table with co2 values with positions id. I changed her Math.Random to the code below:
<?php $result = mysql_query("SELECT * FROM node1 ORDER BY id DESC LIMIT 1")or die(mysql_error());?>
<?php $row = mysql_fetch_array( $result );?>
var j = "<?php echo $row['co2'];?>";
var next = "<?php echo $row['id'];?>";
for (var i = 0; i < this.xscale - 1; i++)
{
this.array[i] = [i,this.array[i+1][1]]; // (x,y)
}
this.array[this.xscale - 1] = [this.xscale - 1,j];
However, when i run this code, the first value changes, after which it remains constant, even though the last row of the table is being updated.
I heard it is because in php, the server is only polled once. Therefore i only get a constant reading of the first data. Is there any way in which i can make the graph update to the last value of the table? with ajax?
Thanks for your help
Yes, you can use Periodic refresh (Polling)
or
HTTP Streaming.
Note that both of these options can be quite bandwidth demanding.
you have to do some sort of polling. But even before you do that,
1. create a php file that retrieves all the important data from the db.
2. let that file echo/return that data in a formatted way.
3. have js function poll that file at intervals (a function that runs in setInterval() )
and yes.. there would be some bandwith issues but i think its manageable.

get max value in php (instead of mysql)

I have two msyql tables, Badges and Events. I use a join to find all the events and return the badge info for that event (title & description) using the following code:
SELECT COUNT(Badges.badge_ID) AS
badge_count,title,Badges.description
FROM Badges JOIN Events ON
Badges.badge_id=Events.badge_id GROUP
BY title ASC
In addition to the counts, I need to know the value of the event with the most entries. I thought I'd do this in php with the max() function, but I had trouble getting that to work correctly. So, I decided I could get the same result by modifying the above query by using "ORDER BY badgecount DESC LIMIT 1," which returns an array of a single element, whose value is the highest count total of all the events.
While this solution works well for me, I'm curious if it is taking more resources to make 2 calls to the server (b/c I'm now using two queries) instead of working it out in php. If I did do it in php, how could I get the max value of a particular item in an associative array (it would be nice to be able to return the key and the value, if possible)?
EDIT:
OK, it's amazing what a few hours of rest will do for the mind. I opened up my code this morning, and made a simple modification to the code, which worked out for me. I simply created a variable on the count field and, if the new one was greater than the old one, changed it to the new value (see the "if" statement in the following code):
if ( $c > $highestCount ) {
$highestCount = $c; }
This might again lead to a "religious war", but I would go with the two queries version. To me it is cleaner to have data handling in the database as much as possible. In the long run, query caching, etc.. would even out the overhead caused by the extra query.
Anyway, to get the max in PHP, you simply need to iterate over your $results array:
getMax($results) {
if (count($results) == 0) {
return NULL;
}
$max = reset($results);
for($results as $elem) {
if ($max < $elem) { // need to do specific comparison here
$max = $elem;
}
}
return $max;
}

Categories