jQuery DataTable with SQLSRV and JSON - javascript

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...

Related

How to add flags for each country in datatables

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.

Error In Displaying Data Records from Database on the console in Json Data format using Ajax in php

I am trying to display database records to my console in json format but i can't see why my request in json format is not being displayed on my console. There is no error also to guide me where i made a mistake. can someone help me. I use the MVC framework for writing my code. I want to retrieve horse names based on race number from the race table in the database.
here is my home.php
<div class="box-body">
Start creating your amazing application!
<table class="table table-bordered table-striped dt-responsive tables" width="100%">
<thead>
<tr>
<th style="width:10px">#</th>
<th>id</th>
<th>Race Number</th>
<th>Horse Name</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<?php
$users = ControllerUsers::ShowallUsersCtr();
foreach ($users as $key => $value) {
echo '
<tr>
<td>'.($key+1).'</td>
<td>'.$value["id"].'</td>
<td>'.$value["racenumber"].'</td>
<td>'.$value["horsename"].'</td>';
echo '<td>
<div class="btn-group">
<button class= "btn btn-primary btnAddRace" RaceNumber="'.$value["racenumber"].'" data-toggle="modal" data-target="#editUser">Add Horse - Race 1</button>
</div>
</td>
</tr>';
}
?>
</tbody>
</table>
</div>
here is my javascript file code named users.js
$(document).on("click", ".btnAddRace", function(){
var RaceNumber = $(this).attr("RaceNumber"); // capture the race number from database to the console
console.log("RaceNumber",RaceNumber);
var data = new FormData();
data.append("RaceNumber",RaceNumber);
$.ajax({
url: "ajax/users.ajax.php",
method: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
dataType: "json",
success: function(answer){
console.log("answer", answer); // bring from the database whatever we asked for
}
});
});
And here is my Ajax file users.ajax.php
<?php
require_once "../controllers/users.controller.php";
require_once "../models/users.model.php";
class AjaxUsers{
public $RaceNumber;
public function ajaxEditUser(){
$item = "racenumber";
$value = $this->RaceNumber; // value what is selected from the table
$answer = ControllerUsers::ctrShowUsers($item, $value); // ask for the controller to show me the race table
echo json_encode($answer);
}
}
if (isset($_POST["RaceNumber"])) { // if the variable race number comes with information, we can execute all of this
$edit = new AjaxUsers();
$edit -> RaceNumber = $_POST["RaceNumber"];
$edit -> ajaxEditUser();
}
here is my user controller and model methods
static public function ctrShowUsers($item, $value){
$table = "race";
$answer = UsersModel::MdlShowUsers($table, $item, $value);
return $answer;
}
static public function MdlShowUsers($table, $item, $value){
$stmt = Connection::connect()->prepare("SELECT * FROM $table WHERE $item = :$item");
$stmt -> bindParam(":".$item, $value, PDO::PARAM_INT);
$stmt -> execute();
return $stmt -> fetch();
$stmt -> close();
$stmt = null;
}
Database Picture is here
enter image description here

How to fetch data to jquery dataTable with form submit

I am inserting data with jquery Ajax using form submit, And fetching data to dataTable after form submit, following code giving DataTables warning: table id=mainTable - Requested unknown parameter '1' for row 0, column 1. . . . .
var mainTable = $('.mainTable').DataTable();
$('#Form').submit(function(e) {
e.preventDefault();
var form = $(this).serialize();
$.ajax({
url: "result.php",
type: "post",
data: form
}).done(function (data) {
mainTable .clear().draw();
mainTable .rows.add(data).draw();
}).fail(function (jqXHR, textStatus, errorThrown) {
});
});
HTML
<div class="content">
<!-- form start -->
<form method="post" id="Form">
<input type="text" name="id">
<input type="text" name="name">
<input type="text" name="class">
<button type="submit">submit</button>
</form>
<table id="mainTable" class="mainTable table table-striped">
<thead>
<tr>
<th>Roll No</th>
<th>Name</th>
<th>class</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
PHP
$id = $_POST['group_id'];
$rollno = $_POST['roll_no'];
$name = $_POST['name'];
$class = $_POST['class'];
$insert = "insert into students (roll_no,group_id,name,class) values(:roll_no,:id,:name,:class)";
$insert = $db->prepare($insert );
$insert ->bindParam(':roll_no',$rollno);
$insert ->bindParam(':id',$id );
$insert ->bindParam(':name',$name);
$insert ->bindParam(':class',$class);
$insert ->execute();
$fetch = "SELECT roll_no,name,class FROM students where group-id=:id";
$fetch = $db->prepare($fetch );
$fetch ->bindParam(':id',$id);
$fetch ->execute();
$output = array('data' => array());
while($row = $fetch ->fetch(PDO:: FETCH_OBJ)) {
$id = $row->roll_no;
$name = $row->name;
$class = $row->class;
$output['data'][] = array( $id,$name,class);
} // /while
echo json_encode($output);
Moved from comment
The root cause is simply because jQuery ajax() doesn't parse the JSON response from result.php. The easiest solution is to parse it inside done():
data = JSON.parse(data);
mainTable.rows.add(data.data).draw();
Another solution is to properly return JSON header in result.php. Line data = JSON.parse(data) in done() should also be omitted:
header('Content-Type: application/json');
echo json_encode($output);

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

Categories

Resources