How to add flags for each country in datatables - javascript

Here is my javascript with flags
<script type="text/javascript">
$(document).ready(function() {
var dataTable = $("#example").DataTable( {
processing: true,
bSort: false,
serverSide: true,
iDisplayLength: 10,
"ajax": {
"url": "json/j-t.php",
"type": "POST"
},
} );
$("#example_filter").css("display","none"); // hiding global search box
$(".example-search-input").on("keyup click change", function () {
var ixoh =$(this).attr("id"); // getting column index
var vxoh =$(this).val(); // getting search input value
dataTable.columns(ixoh).search(vxoh).draw();
if(ixoh != null || ixoh != null){ dataTable.columns(ixoh).search(vxoh).draw(); };
} );
</script>
Here is the file j-t.php
$sql = "SELECT *";
$sql.=" FROM info WHERE type='1' AND sold='0'";
$query=mysqli_query($conn, $sql) or die;
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData;
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["types"];
$nestedData[] = $row["country"];
$nestedData[] = $row["infos"];
$nestedData[] = $row["price"];
$nestedData[] = $row["email"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ),
"recordsTotal" => intval( $totalData ),
"recordsFiltered" => intval( $totalFiltered ),
"data" => $data
);
echo json_encode($json_data);
here is my database
SELECT * FROM `info` WHERE `country` LIKE 'CA' ORDER BY `date_added` DESC
I need to add in Datatables just like contry name CA US DE GB etc... i like to add with flags and Country name in Datatable Country row

You can use column rendering as described here:
https://datatables.net/examples/advanced_init/column_render.html
In your case that would be something like:
var dataTable = $("#example").DataTable({
processing: true,
bSort: false,
/*serverSide: true,*/
iDisplayLength: 10,
/*"ajax": {
"url": "json/j-t.php",
"type": "POST"
},*/
columnDefs: [{
render: function(data, type, row) {
return '<img src="https://flagcdn.com/16x12/' + data.toLowerCase() + '.png">';
},
targets: 1,
}]
});
<html>
<head>
<link href="//cdn.datatables.net/1.13.1/css/jquery.dataTables.min.css" rel="stylesheet" />
</head>
<body>
<table id="example" class="display" style="width:100%">
<thead>
<tr>
<th>Types</th>
<th>Country</th>
<th>Infos</th>
<th>Price</th>
<th>E-Mail</th>
</tr>
</thead>
<tbody>
<tr>
<td>Type A</td>
<td>US</td>
<td>Some info</td>
<td>$1000,00</td>
<td>someone#example.com</td>
</tr>
<tr>
<td>Type B</td>
<td>DE</td>
<td>Some info</td>
<td>€1000,00</td>
<td>someone#example.com</td>
</tr>
<tr>
<td>Type C</td>
<td>GB</td>
<td>Some info</td>
<td>£1000,00</td>
<td>someone#example.com</td>
</tr>
</tbody>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//cdn.datatables.net/1.13.1/js/jquery.dataTables.min.js"></script>
</body>
</html>
For this example I commented out the server-side part and used some fixed HTML data. You can remove the comments for your use.

You could download all of the SVG flags from a place like this ...
https://observablehq.com/#slattery/iso-3166-svg-flags
... then add a column to your database that includes the name associated with your flag file, using an ALTER TABLE info ADD COLUMN query, followed by a bunch of UPDATE queries.
Your PHP logic (or Twig, or Blade, or whatever you're using) would then have to be edited to convert that name into an actual <img> tag for inclusion in the table.

Related

Refresh jquery data table without refreshing the whole page

I want to refresh the jquery datatable every 3 seconds. I already done this but I have pagination issues. When I execute the code the pagination is gone so all the data is display without pagination.
Here is my code:
<div id="timexx">
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
<?php
include('../dist/includes/dbcon.php');
$query=mysqli_query($con,"SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC")or die(mysqli_error());
while($row=mysqli_fetch_array($query)){
$id=$row['id'];
$name=$row['name'];
?>
<tr>
<td>
<?php echo $id;?>
</td>
<td>
<?php echo $name;?>
</td>
</tr>
<?php }?>
</table>
</div>
And this is my javascript code:
$(document).ready(function() {
setInterval(function() {
$('#timexx').load(location.href + " #timexx>*", "")
}, 3000);
});
I would recommend using an ajax data source along with ajax.reload(). In fact, the docs page I linked there has an example of just what you are after.
For your markup you can simply create the table and header:
<table id="example1" class="table table-bordered table-striped" style="margin-right:-10px">
<thead>
<tr>
<th>id #</th>
<th>Name</th>
</tr>
</thead>
</table>
Then initialize datatables with ajax data source, declare your columns and start the loop:
$(document).ready( function () {
var table = $('#example1').DataTable({
"ajax" : 'http://example.com/table_data.php',
"columns" : [
{ "data" : "id" },
{ "data" : "name" )
]
});
setInterval(function () {
// the second argument here will prevent the pagination
// from reseting when the table is reloaded
table.ajax.reload( null, false );
}, 3000);
});
Now you need a web page at the endpoint declared for your ajax data source http://example.com/table_data.php that spits out the table data as a json. There are a few ways this can be structured, but my preference is to use the data property as the docs state:
the data parameter format shown here can be used with a simplified DataTables initialisation as data is the default property that DataTables looks for in the source data object.
With this objective, your php script might look something like this:
include('../dist/includes/dbcon.php');
$query = mysqli_query($con, "SELECT * FROM accounts_tic WHERE statuss = 'New' OR statuss = 'On-Process' order by id DESC") or die(mysqli_error($con));
$results = [];
while ($row=mysqli_fetch_array($query)) {
$results['data'][] = [
'id' => $row['id'],
'name' => $row['name']
];
}
echo json_encode($results);
Side note, mysqli_error() expects a single argument which should be your connection resource.

How to delete row after i select the row and press the button

Screenshot
<?php
if(isset($_GET['View']) && $_GET['View']=="HistoryEntry"){
echo '
<h2>History Of Entries</h2>
<table id="table" class="table table-hover">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Date In</th>
<th scope="col">Date Out</th>
<th scope="col">Rfid</th>
<th scope="col">Plate #</th>
</tr>
</thead>
<tbody>';
global $connection;
$query = "SELECT * FROM history_entries";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result)){
echo '<tr>
<th scope="row">'.$row['Entry_ID'].'</th>
<td>'.$row['Date_in'].'</td>
<td>'.$row['Date_out'].'</td>
<td>'.$row['Acc_rfid'].'</td>
<td>'.$row['Plate_num'].'</td>
</tr>';
}
echo ' </tbody>
</table>
<center>
<button>Delete</button>
</center>
<div class="line"></div>';
}
?>
?>
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
});
$("#Sample").click(function() {
var value = $(".selected th:first").html();
value = value || "No row Selected";
});
As you can see this my codes, i already know how to select the row and get the ID but cant pass the ID "value" to php in order to do the delete function in database. can i use here $.POST function here? or is it better to use GET function here but i think it wouldn't be secure.
This is how you can do it without get param :
1/ Your FRONT :
HTML (just an example)
<table>
<tr id="row_id">
<td>Data 1</td>
<td>Data 2</td>
...
</tr>
...
</table>
<button id="delete_row" type="button">Delete</button>
JS / jQuery
var current_row_id = "";
// You select the row
$("#table tr").click(function() {
$('.selected').removeClass('selected');
$(this).addClass("selected");
current_row_id = $(this).attr("id"); // Here you get the current row_id
});
// You delete the row
$("#delete_row").on("click", function() {
$.ajax({
type: "POST",
url: "delete.php",
data: {"id" : current_row_id }, // You send the current_row_id to your php file "delete.php" in post method
dataType: 'json', // you will get a JSON format as response
success: function(response){
// you do something if it works
},
error: function(x,e,t){
// if it doesn't works, check the error you get
console.log(x.responseText);
console.log(e);
console.log(t);
}
});
});
2/ Your BACK
PHP "delete.php" file
<?php
$id = $_POST['id']; // You get the 'current_row_id' value
// Now you do your DELETE request with this id :
$sql = "DELETE ... WHERE id = :id";
etc...
$result = array(); // You can prepare your response and send information about what you did
$result['row_deleted'] = $id;
$result['message'] = "The row with id = " . $id . " was deleted with success";
$result['type'] = "success";
//etc....
echo json_encode($result); // You send back a response in JSON format
3/ Back to the FRONT
Your ajax call, the success part :
success: function(response){
// You can display a success message for example using your response :
alert(response.message); // You will get 'The row with id = {the row id} was deleted with success' here for example
},
Is it what you are looking for?
here is a simple Ajax request
var data = {
rowId: 1
};
$.ajax({
type: "POST",// GET|POST
url: 'delete.php', // Where you want to send data like url or file
data: data, // this is what you want to send to server, in this case i send data with id = 1 to server
dataType: 'json' // here we say what data type we want "json"
success: function(response) {
alert(response);
}, // this is the callback were u will get response from your server
});
delete.php here is how u can handle this ajax
$rowId = htmlspecialchars($_POST['rowId']);
if ($rowId) {
global $connection;
$query = "DELETE FROM history_entries WHERE Entry_ID = " . $rowId;
$result = mysqli_query($connection, $query);
$response = array(
'success' => true
);
echo json_encode($response);
exit;
} else {
echo json_encode(array('success' => false));
exit;
}
Hope this will help you to understand how to use Ajax

Clickable Data Table Row

I am having a data table which is fetching its data from MySQL database. In my database i am having a column named as "location" which is a link to some audio file. All the rows in the database are having their respective links to their audio files.What i want is that
When i click on any row of the data table the browser should automatically get redirected to the link of their respective audio files.
The Current link that is stored in the database is for local IP. i want to change the link to my public IP before the user is redirected since the local IP won't work on remote server. Below is my code:
data table.php
<?php
/* Database connection start */
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "vici";
$conn = mysqli_connect($servername, $username, $password, $dbname) or die("Connection failed: " . mysqli_connect_error());
/* Database connection end */
// storing request (ie, get/post) global array to a variable
$requestData= $_REQUEST;
$columns = array(
// datatable column index => database column name
0 =>'recording_id',
1 => 'call_date',
2=> 'location',
3=> 'Agent',
4=> 'phone'
);
// getting total number records without any search
$sql = "SELECT recording_id, call_date, location,agent,phone";
$sql.=" FROM goautodial_recordings_view";
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalData = mysqli_num_rows($query);
$totalFiltered = $totalData; // when there is no search parameter then total number rows = total number filtered rows.
$sql = "SELECT recording_id, call_date, location,agent,phone";
$sql.=" FROM goautodial_recordings_view WHERE 1=1";
if( !empty($requestData['search']['value']) ) { // if there is a search parameter, $requestData['search']['value'] contains search parameter
$sql.=" AND ( recording_id LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR call_date LIKE '".$requestData['search']['value']."%' ";
$sql.=" OR agent LIKE '".$requestData['search']['value']."%' )";
}
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$totalFiltered = mysqli_num_rows($query); // when there is a search parameter then we have to modify total number filtered rows as per search result.
$sql.=" ORDER BY ". $columns[$requestData['order'][0]['column']]." ".$requestData['order'][0]['dir']." LIMIT ".$requestData['start']." ,".$requestData['length']." ";
/* $requestData['order'][0]['column'] contains colmun index, $requestData['order'][0]['dir'] contains order such as asc/desc */
$query=mysqli_query($conn, $sql) or die("employee-grid-data.php: get employees");
$data = array();
while( $row=mysqli_fetch_array($query) ) { // preparing an array
$nestedData=array();
$nestedData[] = $row["recording_id"];
$nestedData[] = $row["call_date"];
$nestedData[] = $row["location"];
$nestedData[] = $row["agent"];
$nestedData[] = $row["phone"];
$data[] = $nestedData;
}
$json_data = array(
"draw" => intval( $requestData['draw'] ), // for every request/draw by clientside , they send a number as a parameter, when they recieve a response/data they first check the draw number, so we are sending same number in draw.
"recordsTotal" => intval( $totalData ), // total number of records
"recordsFiltered" => intval( $totalFiltered ), // total number of records after searching, if there is no searching then totalFiltered = totalData
"data" => $data // total data array
);
echo json_encode($json_data); // send data as json format
?>
index.php
<!DOCTYPE html>
<html>
<title>GO VOIP</title>
<head>
<link rel="stylesheet" type="text/css" href="css/jquery.dataTables.css">
<script type="text/javascript" language="javascript" src="js/jquery.js"></script>
<script type="text/javascript" language="javascript" src="js/jquery.dataTables.js"></script>
<script type="text/javascript" language="javascript" >
$(document).ready(function() {
var dataTable = $('#employee-grid').DataTable( {
"processing": true,
"serverSide": true,
"ajax":{
url :"employee-grid-data.php", // json datasource
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
$('.dataTable').on('click', 'tbody td', function() {
//get textContent of the TD
alert('TD cell textContent : ', this.textContent)
//get the value of the TD using the API
('value by API : ', table.cell({ row: this.parentNode.rowIndex, column : this.cellIndex }).data());
})
} );
</script>
<style>
div.container {
margin: 0 auto;
max-width:760px;
}
div.header {
margin: 100px auto;
line-height:30px;
max-width:760px;
}
body {
background: #f7f7f7;
color: #333;
font: 90%/1.45em "Helvetica Neue",HelveticaNeue,Verdana,Arial,Helvetica,sans-serif;
}
</style>
</head>
<body>
<div class="header"><h1>DataTable demo (Server side) in Php,Mysql and Ajax </h1></div>
<div class="container">
<table id="employee-grid" cellpadding="0" cellspacing="0" border="0" class="display" width="100%">
<thead>
<tr>
<th>Recording ID</th>
<th>Call date</th>
<th>Location</th>
<th>Agent</th>
<th>Phone</th>
</tr>
</thead>
</table>
</div>
</body>
</html>
Below is the Screenshot:
method 1 :
change in SQL query (only where you get rows not count)
$sql = "SELECT recording_id, call_date, CONCAT('get song'),agent,phone";
note : if you have some field in mysql like song_name then you display in anchor tag
$sql = "SELECT recording_id, call_date, CONCAT('',song_name,''),agent,phone";
OR
method 2 :
change in PHP while loop
//replace from
$nestedData[] = $row["location"];
to
$nestedData[] = 'get song';
You can do it in simple php with eco like:
echo 'Name of the song';
If you click on it it will redirect you to the file.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "employee-grid-data.php",
success: function(data){
data = JSON.parse(data);
/*Here you will get the data
Loop through the data and append to dataTable*/
$('#employee-grid').DataTable();
},
error : function() { // error handling
$(".employee-grid-error").html("");
$("#employee-grid").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display", "none");
}
});
Use ajax to get JSON data from the server and manually add it to the HTML table, finally initialize datatable.

jQuery DataTable with SQLSRV and JSON

I do not understand what I am doing wrong. Is this not the right format for performing an ajax call and returning JSON?
I am trying to return JSON to populate a DataTable. I have done something very similar to this before, but I am unable to make it work this time.
Here is the script ("api/exceptions_all.php") where I am using SQLSRV to return the JSON:
<?php
include("../include/database.php");
$select = "SELECT
''
,[FOR_PARTNER]
,[FOR_NAME]
,[SHP_PARTNER]
,[SHP_NAME]
,[MODDATE]
,[MODUSER]
,[ID]
FROM [main].[dbo].[for_exceptions]";
$query = sqlsrv_query($dbc, $select) or die(sqlsrv_errors());
$out = array();
while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) )
{
$out[] = $row;
}
echo json_encode( $out );
sqlsrv_free_stmt($query);
?>
Now here is my javascript file ("exceptions.js") where I am trying to retrieve the JSON and print it in the datatable:
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"type": 'POST',
"ajax": 'api/exceptions_all.php',
"data": data,
"dataType": 'json',
"bDestroy": true
});
});
I keep getting an error stating "Uncaught ReferenceError: data is not defined" referring to "data": data above.
In my HTML file, I have the table where the DataTable should be populated:
<table id="example1">
<thead>
<tr>
<th>Edit</th>
<th>FF Partner Code</th>
<th>FF Name</th>
<th>SHP Partner Code</th>
<th>SHP Name</th>
<th>Modified Date</th>
<th>Modified User</th>
<th>ID</th>
</tr>
</thead>
// datatable should be here
</table>
i thing you are missing to declare the $out[] array out of while loop ;
<?php
include("../include/database.php");
$select = "SELECT
''
,[FOR_PARTNER]
,[FOR_NAME]
,[SHP_PARTNER]
,[SHP_NAME]
,[MODDATE]
,[MODUSER]
,[ID]
FROM [main].[dbo].[for_exceptions]";
$query = sqlsrv_query($dbc, $select) or die(sqlsrv_errors());
$out=array();**// add this line**
while( $row = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC) )
{
$out[] = $row;
}
echo json_encode( $out );
sqlsrv_free_stmt($query);
?>
Looks like you're using the DataTables plugin for jQuery...
Something like this maybe...
$(document).ready(function()
{
var $dataTable = $('#example1').DataTable({
"ajax": 'api/exceptions_all.php'
});
});
This is directly from the Docs...

Table is not refreshed asynchronously AJAX,JQuery and PHP

I am trying to add a new row to the existing table using Ajax, PHP and Jquery.
Ajax call is successful (tested it by placing alerts). But it displays the new row only if I refresh the entire page. I want the row to be added to the table with out refreshing the entire page, but just with a table refresh on the fly.
example : As I press Add button on the table, it should add a new row to the table on the fly.
hotTopics_focusAreas_data.php file :
<?php
$SQL = "select * from hottopics order by id desc limit 1";
while($row = mysql_fetch_array($SQL,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
Javascript file :
$("document").ready(function() {
hotAddClicked();
});
function hotAddClicked(){
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table").append(data);
}
});
});
}
Table definition:
<table class="table" id="hottopics_table">
<thead>
<tr>
<th>Title</th>
<th>Status</th>
<th></th>
</tr>
</thead>
<tbody>
<?php
$SQL = "select * from hottopics;";
$result_update = mysql_query($SQL) or die("Couldn't execute query.".mysql_error());
while($row = mysql_fetch_array($result_update,MYSQL_ASSOC)) {
echo
"<tr>
<td id=title:".$row['id']." contenteditable='true'>".$row['title']."</td>
<td id=status:".$row['id']." contenteditable='true'>".$row['status']."</td>
<td><button type='button' class='btn btn-danger'>Delete</button></td>
</tr>";
}
?>
</tbody>
</table>
$(document).ready(function() {
$("#hotadd_clicked").click(function(e) {
endpoint = 'hotTopics_focusAreas_data.php?role=add';
$.ajax({
url : endpoint,
type : "GET",
async : true,
success : function(data) {
$("#hottopics_table tbody").append(data);
}
});
});
});
Check this jQuery script and check if it works properly.

Categories

Resources