Displaying data using AJAX PHP - javascript

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 );
}

Related

Adding DropDown list in jQuery DataTable

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"]?

Having trouble with datatable invalid JSON response

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();
}
?>

jQuery DataTables column sorting on other column

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.

Displaying checkbox dynamically in PHP/JavaScript

A benefit can be assigned to an employee but firstly the code below shows the dynamic dropdown of employee and dynamic benefit checkboxes
<?php
$ctr = 0;
$employee = mysqli_query($conn, "SELECT * FROM housekeeping_employee") or DIE("Could not Select");
echo "<select class='indent' name = 'Employee'>";
while($listEmployee = mysqli_fetch_array($employee))
{
echo "<option value = ".$listEmployee['employeeid'].">".$listEmployee['firstname']."</option>";
}
echo "</select>";
echo "<br><be>";
echo "<div class='indent'>";
$benefits = mysqli_query($conn, "SELECT * FROM housekeeping_benefit")or DIE("SELECT Query not working.");
if(mysqli_num_rows($benefits))
{
while($row = mysqli_fetch_array($benefits))
{
$ctr++;
echo "<h6><input type = 'checkbox' name = 'benefits".$ctr."' value ='".$row['benefitid']."' >".$row['benefitname']." </input></h6> <be>";
if($ctr == 5){
echo"<br>";
$ctr=0;
}
}
echo "<br><input type='submit' class='btn btn-info' name='insert' value='Submit'/>";
}
echo "<input type='hidden' name='ctr' value='".$ctr."'/>";
echo "</form>";
?>
This is what the insert code of assigning benefits to employee looks like.
$employeeid = $_POST['Employee'];
for($a = 1; $a <= $_POST['ctr'] ; $a++)
{
if(isset($_POST['benefits'.$a]))
{
$benefitid = $_POST['benefits'.$a];
//echo "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')";
mysqli_query($conn, "INSERT INTO `housekeeping_employeebenefits`(`employeeid`,`benefitid`) VALUES('$employeeid','$benefitid')") or DIE("Insert query is not working");
echo "Employee to Benefits successful!";
}
}
My main problem is how will I display checked checkboxes if the employee already has that benefit? I'm really lost

Convert Array of Objects

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"],
);
}

Categories