I am trying to make the rows in my DataTable clickable. On click I want to navigate the user to another page.
When I execute the script and click on the rows the script always navigates me to ./test/data.php?id=1 which is the page I want to use for the first row. The same script is active in all the rows.
Does someone know why my script is pasting the link for the first row in all the rows and how I can fix this?
Here is my script:
<script type="text/javascript">
$( document ).ready(function() {
$('#grid1').DataTable({
"bprocessing": true,
"serverSide": true,
"ajax": {
"url": "response2.php",
"type": "POST",
"error": function(){
$("#grid_processing").css("display","none");
}
},
"columnDefs": [
{ "targets": 1, "render": function ( data, type, full, meta ) { return '<b>'+data+'</b>'} },
{ "targets": 3, "render": function ( data, type, full, meta ) { return '<i>'+data+'</i>'} },
{ "targets": 6, "render": function ( data, type, full, meta ) { return '<a href="./test/data.php?id='+data+'"></a>'; } }
]
});
});
</script>
<script type="text/javascript">
$(document).ready(function() {
$('#grid1').click(function() {
var href = $(this).find("a").attr("href");
if(href) {
window.location = href;
}
});
});
</script>
Edit 1:
response2.php:
<?php
include_once("connection.php");
$params = $columns = $totalRecords = $data = array();
$params = $_REQUEST;
$columns = array(
0 => 'name',
1 => 'address',
2 => 'number',
3 => 'city',
4 => 'country',
5 => 'id'
);
$where = $sqlTot = $sqlRec = "";
if( !empty($params['search']['value']) ) {
$where .=" WHERE ";
$where .=" ( id LIKE '".$params['search']['value']."%' ";
$where .=" OR name LIKE '".$params['search']['value']."%')";
}
if (!empty($where) ) {
$where .= "AND user_id='1' ";
} else {
$where .= "WHERE user_id='1' ";
}
$sql = "SELECT name, address, number, city, country, id FROM customers ";
$sqlTot .= $sql;
$sqlRec .= $sql;
if(isset($where) && $where != '') {
$sqlTot .= $where;
$sqlRec .= $where;
}
$sqlRec .= " ORDER BY id DESC LIMIT ".$params['start']." ,".$params['length']." ";
$queryTot = mysqli_query($conn, $sqlTot) or die("database error:". mysqli_error($conn));
$totalRecords = mysqli_num_rows($queryTot);
$queryRecords = mysqli_query($conn, $sqlRec) or die("error to fetch employees data");
while( $row = mysqli_fetch_row($queryRecords) ) {
$data[] = $row;
}
$json_data = array(
"draw" => intval( $params['draw'] ),
"recordsTotal" => intval( $totalRecords ),
"recordsFiltered" => intval($totalRecords),
"data" => $data
);
echo json_encode($json_data);
?>
$(this).find("a")will always find the first anchor tag it comes across which is the first row. Hence it is redirecting to./test/data.php?id=1every time.You clicked on 1's row. I tried to use<thead>an<tr>in my script but the result is the same. I still getYou clicked on 1's row.