My jQuery Datatable is not sorting properly in some columns. When I sort the GGC_ID column, it's sorting properly, but when I sort the CustomerID column, its not sorting. And when I sort the Customer Name column, the CustomerID column is the one that is sorting.
Here's my code:
record.js:
var tbl = $('#tbl').DataTable({
"processing": true,
"serverSide": true,
"order": [],
"searchable": true,
"columnDefs": [
{
"orderable": false,
"targets": [0,4]
}
],
"ajax": {
url: "fetch.php",
method: "POST"
}
});
fetch.php
$query = '';
$query .= "SELECT records.GGC_ID, company.Comp_Name, customer.CUST_ID, customer.CUST_NAME FROM records INNER JOIN company on company.Comp_ID = records.COMP_ID INNER JOIN customer ON customer.CUST_ID = records.CUST_ID ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE Comp_Name LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR CUST_NAME LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR GGC_ID LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"])) {
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].
' ';
} else {
$query .= "ORDER BY GGC_ID DESC ";
}
if($_POST["length"] != -1) {
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$stmt = $db->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll();
$data = array();
$filtered_rows = $stmt->rowCount();
foreach ($result as $row) {
$sub_array = array();
$sub_array[] = $row["Comp_Name"];
$sub_array[] = $row["GGC_ID"];
$sub_array[] = $row["CUST_ID"];
$sub_array[] = $row["CUST_NAME"];
$sub_array[] = '<button type="button" name="update" id="'.$row["CUST_ID"].'"
class = "btn btn-default details" data-toggle="modal" data-target="#customer_modal">Details</button> ';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
$_REQUEST["order"][0][column] - does not have field name, it has index of field in columns
$index = $_REQUEST["order"][0][column];
ORDER BY $_REQUEST["columns"][ $index ]["name"]
You can open google console, network tab, find server request - header tab to see variables it sends.
Also
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
exit();
Your fixed code:
$index = $_POST['order']['0']['column'];
$field = $_POST["columns"][ $index ]["name"];
$query .= 'ORDER BY '.$field.' '.$_POST['order']['0']['dir'].
' ';
When you sort the Customer Name column, echo $query, check sql is right.
Related
I want to display table's data with jQuery DataTable and sometimes apply an extra data filtering, using the output of a dropdown select input.
The main code for fetching data (fetch.php) is:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$sub_array = array();
$sub_array[] = $row["part_manufacturer"];
$sub_array[] = $row["part_id"];
$sub_array[] = $row["part_category"];
$sub_array[] = $row["part_stock"];
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
while the DataTable is defined in index.php as follows:
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"ajax":{
url:"actions/fetch.php",
type:"POST"
},
"columnDefs":[
{
"targets":[0, 1],
"orderable":false,
},
],
});
In index.php, i've created 3 dependent dropdown lists, which load data from other tables. Now, i want to take the id of 3rd dropdown list and update the data of Part_tb in fetch.php accordingly. Below, you can see that when 3rd dropdown change, i call a function load_parts():
$(document).on('change', '#sub3_category_item', function(){
load_parts();
});
function load_parts()
{
var action = 'fetch_data';
var filter_part_id = $('#sub2_category_item').val();
$.ajax({
url:"actions/fetch.php",
method:"post",
data:{action:action, filter_part_id:filter_part_id},
success:function(data)
{
$('#user_data').DataTable().ajax.reload();
}
});
}
The problem is that i can't filter the data of fetch.php according to the selected id of #sub2_category_item. Could you help me on that?
I've modified the index.php as follows:
$(document).on('change', '#sub3_category_item', function(){
var filter_part_id = $('#sub3_category_item').val();
$('#user_data').DataTable().destroy();
fill_datatable(filter_part_id);
});
fill_datatable();
function fill_datatable(filter_part_id = '')
{
var dataTable = $('#user_data').DataTable({
"processing":true,
"serverSide":true,
"order":[],
"searching" : false,
"ajax":{
url:"actions/fetch.php",
type:"POST",
data:{filter_part_id:filter_part_id}
}
});
and fetch.php:
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST['filter_part_id']) && $_POST['filter_part_id'] != '')
{
$query .= "SELECT * FROM Part_tb WHERE part_id IN (SELECT pcfit_name from Part_car_fit_tb WHERE pcfit_id ='".$_POST["filter_part_id"]."') ";
}
but dataTable crashes, when #sub3_category_item is selected. Any idea, how to filter datatable with the value $_POST["filter_part_id"]?
I keep having this error. I manage to track down the response by inspecting the dataTable which lead me to believe that this is the source of the problem. Please bear with me for I'm still a beginner in javascript and PHP.
image link to error:
source of error
here are my codes:
config.php
<?php
class dbConfig {
protected $serverName;
protected $userName;
protected $password;
protected $dbName;
function dbConfig() {
$this -> serverName = 'localhost';
$this -> userName = 'root';
$this -> password = '';
$this -> dbName = 'database';
}
}
?>
user.php
<?php
require('config.php');
class User extends dbconfig {
protected $hostName;
protected $userName;
protected $password;
protected $dbName;
private $userTable = 'user';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$database = new dbConfig();
$this -> hostName = $database -> serverName;
$this -> userName = $database -> userName;
$this -> password = $database -> password;
$this -> dbName = $database -> dbName;
$conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
} else{
$this->dbConnect = $conn;
}
}
}
private function getData($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
private function getNumRows($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$numRows = mysqli_num_rows($result);
return $numRows;
}
public function userList(){
$query = "SELECT * FROM ".$this->userTable." ";
if(!empty($_POST["search"]["value"])){
$query .= 'where(user_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_fname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_mname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_lname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_address LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_contactnumber LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_birthdate LIKE "%'.$_POST["search"]["value"].'%") ';
}
if(!empty($_POST["order"])){
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
} else {
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1){
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$result = mysqli_query($this->dbConnect, $query);
$numRows = mysqli_num_rows($result);
$userData = array();
while ($user = mysqli_fetch_assoc($result)) {
$userRows = array();
$userRows[] = $user['user_id'];
$userRows[] = ucfirst($user['user_fname']);
$userRows[] = $user['user_mname'];
$userRows[] = $user['user_lname'];
$userRows[] = $user['user_address'];
$userRows[] = $user['user_contactnumber'];
$userRows[] = $user['user_birthdate'];
$userRows[] = '>button type="button" name="update" id="'.$user['user_id'].'"class="btn btn-warning btn-xs update"<Update>/button<';
$userRows[] = '>button type="button" name="delete" id="'.$user['user_id'].'"class="btn btn-danger btn-xs update"<Delete>/button<';
$userData[] = $userRows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $userData
);
echo json_encode($output);
}
}
?>
ajax.js
$(document).ready(function(){
var userRecords = $('#userList').DataTable({
"lengthChange": false,
"processing": true,
"serverSide": true,
"order":[],
"ajax":{
url:"process.php",
type: "POST",
data: {action: 'listUser'},
dataType: "json"
},
"columnDefs":[
{
"targets": [0, 6, 7],
"orderable": false,
},
],
"pageLength": 10
});
});
process.php
<?php
include('user.php');
$user = new User();
if (!empty($_POST['action']) && $_POST['action'] == 'listUser') {
$user -> userList();
}
?>
I am making a website with organizations. You can request to become part of an organizations. But the organizationshas to get a user limit of 500 people. it doesn't give an error and it won't go to my function either. Normally it just has to check if current_users is less then 500. And then the function has to update the user table and the organization.
this is what I tried so far:
<?php
require '../conn.php';
include '../session.php';
$count = "SELECT `current_users` FROM `organisations` WHERE `org_id` =
'".$_POST['org']."'";
$result = mysqli_query($conn, $count); // your query execution
$row = mysqli_fetch_array($result);
if($row['current_users'] < 500){
$this->requestUserCreate()
} else {
throw new Exception('Limit reached')
}
function requestUserCreate() {
$q = "UPDATE `organisations` SET `current_users` = `current_users` + 1 WHERE
`org_id`='".$_POST['org']."'";
$sql = "UPDATE `users` SET `active`= 1, `type` = 0 WHERE `user_id` = '" .
$_POST['user'] . "'";
if ($conn->query($sql) && $conn->query($q) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
?>
this is my table for the organizations
CREATE TABLE `organisations` (
`org_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`path` varchar(100) NOT NULL,
`type` int(1) NOT NULL,
`branche` varchar(50) NOT NULL,
`niveau` int(11) DEFAULT NULL,
`current_users` int(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
and this is for the users:
CREATE TABLE `users` (
`user_id` int(5) NOT NULL,
`fnln` varchar(100) NOT NULL,
`username` varchar(100) NOT NULL,
`password` varchar(100) NOT NULL,
`org_id` int(5) DEFAULT NULL,
`part_id` int(11) NOT NULL DEFAULT '0',
`type` int(1) NOT NULL,
`active` int(11) NOT NULL DEFAULT '1'
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
my javascript
function approveOne(user, org) {
swal({
title: 'Are you sure to approve this users?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Approve user'
}).then(function () {
$.ajax({
url: "functions/save/approveUser.php",
type: "POST",
data: {user, org},
success: function (data) {
swal(
'Approved!',
'You have approved the selected user.',
'Success'
);
$("#newUsers").hide(250);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
}
and here is my html
<!doctype html>
<html lang="en">
<head>
<?php include 'include/header.php'; ?>
<title>Student Concepts | Users</title>
</head>
<?php
if (isset($_SESSION['type'])) {
if ($_SESSION['type'] != '1') {
header('Location: index');
die();
}
}
function getUsers($orgID, $type)
{
require 'functions/conn.php';
$sql = "SELECT users.*, parts.* FROM users INNER JOIN parts ON users.part_id
= parts.part_id WHERE users.org_id = '" . $orgID . "' AND users.active = '"
. $type . "';";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<tr id="' . $row['user_id'] . '">';
echo ' <td>' . $row['fnln'] . '</td>';
echo ' <td>' . $row['username'] . '</td>';
echo ' <td>' . $row['name'] . '</td>';
echo ' <td>';
if ($row['active'] == 0 || $row['active'] == 2) {
echo ' <button class="button button-green"
onclick="approveOne('.$row['user_id'].',
'.$_SESSION['org_id'].')">Approve</button>';
}
echo ' <button class="button button-red"
onclick="deleteFromRelation(' . $row['user_id'] .
');">Delete</button><br/>';
echo ' </td>';
echo '</tr>';
}
}
}
?>
You need to parse the result of the query. Also, you have a logic error in the if if ($count > 500) should be if ($count < 500) because you want to add when you have less then 500
$result = mysqli_query($conn, $count);
if ($result !== false) {
$totalRows = mysqli_num_rows($result);
if ($totalRows < 500) {
$this->requestUserCreate();
} else {
throw new Exception('Limit reached');
}
} else {
echo "Error: " . $count . "<br>" . mysqli_error($conn);
}
Now, an optimisation will be to remake the query, to use a count() function instead of select
Flow of the program:
1. Upon load of the page, the chart will display the total sales of all the branches.
2. When you choose a branch from the dropdown button, the data shown by the chart is the total sales of that specific branch.
My problem is when I click an specific branch the data wont show at all.
Please refer to the screenshot and Code for more information.
Screenshot:
Screenshot of the page when it loads
Screenshot of the page when I choose a branch
PHP Code for data:
<div class="report-header">
<h5 class="report-title">Total Yearly Sales</h5>
<div class="branch-report">
<select class="form-control" id="t-yearly">
<option value="">Branch</option>
<?php
require_once "connect.php";
$sql = "SELECT id,branch FROM tblLocation";
$result = mysqli_query($conn,$sql);
while ($row = mysqli_fetch_array($result)) {
echo "<option value='".$row['id']."'>".$row['branch']."</option>";
}
?>
</select>
</div>
</div>
<div id="t-yearly-sales" style="height: 80%;"></div>
<?php
include "connect.php";
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
$chart = '';
while ($row = mysqli_fetch_array($result)){
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
?>
<script>
new Morris.Bar({
element: 't-yearly-sales',
data: [<?php echo $chart; ?>],
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
</script>
AJAX Code:
//Total Yearly Sales
$("#t-yearly").change(function(){
var branch = $(this).val();
$.ajax ({
url:"fetch_yearly_sales.php",
method: "POST",
data: {branch:branch},
success: function(branch_data){
new Morris.Bar({
element: 't-yearly-sales',
data: [branch_data],
xkey: 'year',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
console.log(branch);
}
});
});
Fetch_Yearly_Sales.php Code:
<?php
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST['branch']);
if($data == ""){
$output = "";
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
ob_clean();
echo $output;
}
else{
$output = "";
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
ob_clean();
echo $output;
}
?>
You can try this in PHP
if($data == ""){
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_assoc($result)) {
$chart = '{year:'.$row["year"].', sales:'.$row["sales"].'},';
}
echo $chart;
} else {
$sql = "SELECT branch_id, year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$chart = '{year:'.$row["year"].', sales:'.$row["sales"].'}';
}
echo $chart;
}
The last comma is invalid. You should really consider using json_encode.
while ($row = mysqli_fetch_assoc($result)) {
$chart .= "{year:'".$row["year"]."', sales:".$row["sales"]."},";
}
echo $output;
Also you're not printing anything:
$output = "";
echo $output;
but you use $chart .= ""; to prepend data.
json_encode example:
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode( $arr );
Whole ajax example:
require "connect.php";
$data = mysqli_real_escape_string($conn,$_POST['branch']);
if($data == ""){
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales GROUP BY year";
$result = mysqli_query($conn, $sql);
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode( $arr );
}
else{
$sql = "SELECT year, SUM(sales) AS sales FROM tblSales WHERE branch_id='".$data."' GROUP BY year";
$result = mysqli_query($conn, $sql);
$arr = array();
while ($row = mysqli_fetch_assoc($result)) {
$arr[] = $row;
}
echo json_encode( $arr );
}
I'm trying to convert my postcodes and towns in an array of JSON objects, but I guess I'm not doing it right, I need it for my autocomplete functionality.
Here is my code:
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
// [ { label: "Choice1", value: "value1" }, { label: "Choice2", value: "value2" } ]
$dname_list[] = "{label:".$row['postcode'].","."value:".$row['town']."}";
}
header('Content-Type: application/json');
echo json_encode($dname_list);
Don't try to insert json with strings. You can rely entirely on json_encode.
This is how i would do
$sql = "SELECT * FROM uk_postcodes";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result))
{
$dname_list[] = array(
"label" => $row['postcode'],
"value" => $row['town']
);
}
header('Content-Type: application/json');
echo json_encode($dname_list);
You need to make each entry in your object an array. This should work:
while($row=mysqli_fetch_array($result)){
$matches[] = array(
'label'=> $row["postcode"],
'value'=> $row["town"],
);
}