I'm trying to do a simple table and the data is populated by php/mysql on wordpress.
My objective is: when the user click on a <th>
, the ajax will reload the table with a get
parameter, so the table will be ordered by the specific column.
If I access my URL like this: localhost/table?data=desc or localhost/table?data=asc
it works, but I want to do that with ajax. Here's part of my code:
JS:
$(document).on('click','#order_data',function() {
$.ajax({
url: '/table?data=desc',
type: 'GET',
success: function(msg) {
$("#main_container").load(location.href + " #table_demos");
}
});
});
});
HTML
<div id="main_container">
<table class="table table-striped table-bordered table-hover" id="table_demos">
<thead>
<th id="order_data">Data
<?php
if(isset($_GET['data']) && $_GET['data'] == 'asc') {
echo '<i class="fa fa-arrow-up" aria-hidden="true"></i>';
} else if(isset($_GET['data']) && $_GET['data'] == 'desc') {
echo '<i class="fa fa-arrow-down" aria-hidden="true"></i>';
}
?>
</th>
<th>Versus</th>
<th>Mapa</th>
<th>Placar</th>
<th>Baixar</th>
</thead>
<tbody>
<?php
$conexao = mysqli_connect("localhost","root","321","local_test");
if(mysqli_connect_errno()) {
echo "Falha na conexão MySQL.";
} else {
$data = '';
if(isset($_GET['data'])) {
if($_GET['data'] == 'asc') {
$data = 'order by data asc';
} else if($_GET['data'] == 'desc') {
$data = 'order by data desc';
}
}
$query = mysqli_query($conexao,"SELECT * FROM demo_cadastro {$data}");
while ($row = mysqli_fetch_assoc($query)) {
echo '<tr>';
echo '<td>' . transformar_data($row['data']) . '</td>';
echo '<td><a href="' . $row['link_adversario'] . '" target="_blank">' . $row['nome_adversario'] . '</a></td>';
echo '<td>' . $row['mapa'] . '</td>';
echo '<td>' . $row['pontos_marcados'] . 'x' . $row['pontos_sofridos'] . '</td>';
if($row['link_demo'] == '#') {
echo '<td><a href="' . $row['link_demo'] . '" class="demo-indisponivel-swal"><i class="fa fa-cloud-download" aria-hidden="true"></i></a></td>';
} else {
echo '<td><a href="' . $row['link_demo'] . '"><i class="fa fa-cloud-download" aria-hidden="true"></i></a></td>';
}
echo '</tr>';
}
mysqli_free_result($query);
}
mysqli_close($conexao);
function transformar_data($data) {
$data_explode = explode('-', $data);
return $data_explode[2] . '/' . $data_explode[1] . '/' . $data_explode[0];
}
?>
</tbody>
</table>
</div>
I think i'm messing up just the ajax call...
Thanks in advice!
</div>
Something like this?
$(document).on('click','#order_data',function() {
$("#main_container").load('/table?data=desc');
});
(You are sort of mixing ajax call and the load-functionality. I believe the latter will work for you.)