I would assign an ID to the th in thead for the table which correspond to you columns in the SQL-table.
$("table thead th").click(function(){
$.getJSON('ajax/get_results.php',
{sortby: $(this).attr('id')},
function(data) {
$.each(data, function(){
// fill table here
}
});
});
You could create some function for sorting the table that you also could use for changing page with AJAX if you are not already doing it.
And on the backend then sort with SQL
"SELECT * FROM table ORDER BY ".$_GET['sortby']
Of course you should secure that sortby, for example filter it with an array of allowed values. I would suggest creating an array with allowed column sort names and using the array_intersect() function to only filter out the allowed values or just check with
if(isset($allowed_columns[$_GET['sortby']]))
Then just output it all in JSON by putting all the results in an array and then:
echo json_encode($array_with_results);
I guess you would like to output somthing like this in JSON:
{
{col1: 'row1',col2: 'row1',col3: 'row1'},
{col1: 'row2',col2: 'row2',col3: 'row2'},
{col1: 'row3',col2: 'row3',col3: 'row3'}
}