changing warning message in datatable - javascript

I have datatable and i have advance search using two combo box my problem is if i search some data and the data doesnt exist it shows warning like this DataTables warning: table id=myTable - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1. Now i want to change the warning like no job exist. Help me pls. im just student sorry for my english
this my code in my search.php
<section>
<div class="container">
<div class="row">
<div class="col-md-12">
<form id="myForm" class="form-inline">
<div class="form-group">
<label>Experience</label>
<select id="experience" class="form-control" name="exp">
<option disabled selected>Select Experience</option>
<?php
$sql = "SELECT DISTINCT(experience) FROM job_post WHERE experience is not null";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row['experience']."'>".$row['experience']."</option>";
}
}
?>
</select>
</div>
<div class="form-group">
<label>Qualification</label>
<select id="qualification" class="form-control" name="qua">
<option disabled selected>Qualification</option>
<?php
$sql = "SELECT DISTINCT(qualification) FROM job_post WHERE qualification is not null";
$result=$conn->query($sql);
if ($result->num_rows>0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='".$row['qualification']."'>".$row['qualification']."</option>";
}
}
?>
</select>
</div>
<button id="" class="btn btn-success">Search</button>
</form>
</div>
</div>
<div class="row" style="margin-top: 5%;">
<div class="table-responsive">
<table id="myTable" class="table" style="width: 1190px;">
<thead>
<th>Job Name</th>
<th>Job Description</th>
<th>Minimum Salary</th>
<th>Maximum Salary</th>
<th>Experience</th>
<th>Qualification</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</section>
<script src="js/jquery-3.3.1.min.js"></script>
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<script type="text/javascript">
$(function(){
var oTable = $('#myTable').DataTable({
"autoWidth" : false,
"ajax" : {
"url" : "refresh_job_search.php",
"dataSrc": "",
"data" : function(d){
d.experience = $("#experience").val();
d.qualification = $("#qualification").val();
}
}
});
$("#myForm").on("submit", function(e){
e.preventDefault();
oTable.ajax.reload(null, false);
});
});
</script>
and this is my refresh_job_search.php
<?php
session_start();
require_once("db.php");
$sql = "SELECT * FROM job_post";
if (!empty($_GET['experience'])) {
$sql = $sql." WHERE experience = '$_GET[experience]'";
}
if (!empty($_GET['qualification']) && !empty($_GET['experience'])) {
$sql = $sql." AND qualification = '$_GET[qualification]'";
}else if(!empty($_GET['qualification'])){
$sql = $sql." WHERE qualification = '$_GET[qualification]'";
}
$result=$conn->query($sql);
if ($result->num_rows>0) {
while($row=$result->fetch_assoc()){
$json[] = array(
0 => $row['jobtitle'],
1 => $row['description'],
2 => $row['minimumsalary'],
3 => $row['maximumsalary'],
4 => $row['experience'],
5 => $row['qualification'],
);
}
echo json_encode($json);
}

Related

Codeigniter 3 using datatable cant get data using ajax

I found an error with my coding.
I here want to display data in DataTables with ajax. For the filter itself, it is dynamic so that the filter can be more than 1 depending on what is made. But when I want to display the data, there is an error which I don't know which side is the error. Here's the script:
By the way, im using CodeIgniter 3
View
<section class="content-header">
<div class="row" style="margin-left:15px; margin-right:15px; margin-bottom: 15px; ">
<div style="background-color: #E9fbf0; background-repeat:no-repeat; background-size:contain; background-position:center; padding: 30 0 0 10; border-radius: 15px; border:1px solid black;">
<div class="col-md-12">
<div class="table-responsive">
<table class="table" style="width: 100%;">
<tr>
<th class="action-th">Departemen</th>
<td><? echo $biodataSiswa['departemen']; ?></td>
</tr>
<tr>
<th class="action-th">Tahun Ajaran</th>
<td><? echo $biodataSiswa['tahunajaran']; ?></td>
</tr>
<tr>
<th class="action-th">Kelas</th>
<td><? echo $biodataSiswa['kelas']; ?></td>
</tr>
<tr>
<th class="action-th">NIS</th>
<td><? echo $biodataSiswa['nis']; ?></td>
</tr>
</table>
</div>
</div>
<input type="hidden" id="idmodul" name="idmodul" value="<? echo $idtabel; ?>"/>
<form id="filter-form">
<div class="row">
<? $no = 0;
foreach ($filter as $row) { ?>
<div class="col-md-3 col-sm-6 mb-3">
<label for=""><? echo $row?></label>
<select class="form-control" id="f_<? echo $no; ?>" name="f_<? echo $no; ?>">
<option value=''>Pilih</option>
<? foreach ($f_[$no] as $row) : ?>
<option value='<? echo $row['f1']; ?>'><? echo $row['f2']; ?> </option>
<? endforeach; ?>
</select>
</div>
<? $no++;} ?>
<br>
</div>
<div style="margin-top:20px;">
<input type="submit" name="submit" value="Filter" class="btn btn-primary d-inline">
</div>
</form>
<div class="row">
<div class="col-md-12">
<br>
<div class="table-responsive">
<table class="table table-bordered" id="example" style="width:100%;">
<thead>
<tr>
<th>Pelajaran</th>
<th>Nilai Angka</th>
<th>Nilai Huruf</th>
<th>Keterangan</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
<!-- <div class="col-md-12">
<br>
<div class="table-responsive">
<table class="table table-bordered" id="example">
<thead>
<tr>
<th>Pelajaran</th>
<th>Nilai Angka</th>
<th>Nilai Huruf</th>
<th>Keterangan</th>
</tr>
</thead>
</table>
</div>
</div> -->
</div>
</div>
</section>
<div class="control-sidebar-bg"></div>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var dataTable;
// var id = $('#idmodul').val();
dataTable = $('#example').DataTable({
"ajax": {
url : "<? echo base_url('viewtabel/ambil'); ?>",
type: "POST",
data: {
filter_data : function(){
return $('#filter-form').serialize();
},
idmodul : function(){
return $('#idmodul').val();
}
}
},
"columnDefs": [{
"defaultContent": "-",
"targets": "_all"
}],
"aoColumns": [
{data : "f1"},
{data : "f2"},
{data : "f3"},
{data : "f4"}
],
"scrollCollapse": true,
"fixedColumns": {
"left": 1
},
'processing': true,
'language': {
"loadingRecords": ' ',
"processing" : '<i class="fa fa-spinner fa-spin" style="font-size:24px;color:rgb(75, 183, 245);"></i>'
},
"scrollX": true,
});
$('#filter-form').submit(function(e){
e.preventDefault();
dataTable.ajax.reload();
})
});
</script>
And, this is the Controller
<?
Header('Access-Control-Allow-Origin: *'); //for allow any domain, insecure
Header('Access-Control-Allow-Headers: *'); //for allow any headers, insecure
Header('Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE'); //method allowed
class Viewtabel extends CI_Controller{
function __construct() {
parent::__construct();
$this->load->helper('url');
$this->load->helper(array('path'));
$this->load->model('M_siswa');
$this->load->library('session');
$this->load->model('M_all');
$this->load->library('lib_connection');
$this->load->library('lib_menu');
$this->load->library('lib_menu_akademik');
$this->load->library('lib_changedate_toindo');
$this->load->library('lib_menu_departemen');
$this->db2 = $this->load->database('jibA', TRUE);
$this->db3 = $this->load->database('jibB', TRUE);
}
public function index() {
$accessToken = $this->session->userdata('token');
$link_api = $this->session->userdata('link_api');
$data['data_website'] = $this->M_all->getWesbiteData();
$arr_segment=$this->uri->segment_array();
if(isset($arr_segment[2])){
$action=strtolower(urldecode($arr_segment[2]));
} else
$action="";
switch($action){
default:
echo "Modul Tabel";
break;
case "load":
$data['data_website'] = $this->M_all->getWesbiteData();
$data['rows_menu3'] = $this->lib_menu_akademik->generate_menu();
$nis = $this->session->userdata('nis');
$emailtagihan = $this->session->userdata('email');
$bioSiswa = $this->M_siswa->getSiswaWithNis($nis,$emailtagihan);
$dataSiswa = $this->M_siswa->getDataByNis($nis);
$idKelas = $dataSiswa['idkelas'];
$id = $arr_segment[3];
$dataTabel = $this->M_all->getDataTabel($id);
$this->session->set_userdata('idmodul',$id = $arr_segment[3]);
$arrFilter = explode(',', $dataTabel['nama_filter']);
$arrQueryF = explode(' | ', $dataTabel['query_filter']);
$connection_id = $dataTabel['connection'];
$arrQueryF=str_replace('#NIS', "'".$nis."'",$arrQueryF);
$arrQueryF=str_replace('#DEPART', "'".$bioSiswa['departemen']."'",$arrQueryF);
// print_r($arrQueryF);
// print_R($arrQueryF);
for ($i = 0; $i < count($arrQueryF); $i++){
$arrQ[] = $this->M_siswa->getFilter($arrQueryF[$i]);
$data['f_'][$i] = $arrQ[$i];
}
$data['filter'] = $arrFilter;
// print_r($dataTabel['pk_tablebaru']);
$data['idtabel'] = $dataTabel['pk_tablebaru'];
$data['biodataSiswa'] = $bioSiswa;
$tglIndo = $this->lib_changedate_toindo->ubahIndo($bioSiswa['tgllahir']);
$data['tgllahirsiswa'] = $tglIndo;
$this->load->view("v_modultabel2.inc.php",$data);
break;
case "setting":
$ch5 = curl_init($link_api. 'extrarest/login-user');
curl_setopt($ch5, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $accessToken));
curl_setopt($ch5, CURLOPT_RETURNTRANSFER, true);
$oUser2 = json_decode(curl_exec($ch5));
$dept_uid = $oUser2->department;
$listmenu = $this->M_all->getMenuFromDepartemen($dept_uid);
$data['menuPerDept'] = $listmenu;
$data['menunya'] = $this->M_all->getMenu();
//$data['rows_menu'] = $this->lib_menu->generate_menu();
$data['rows_menu2'] = $this->lib_menu_departemen->generate_menu($dept_uid,$this->session->userdata('group'),$this->session->userdata('uid'));
$ch1 = curl_init($link_api. 'user/'. $this->session->userdata('uid'));
curl_setopt($ch1, CURLOPT_HTTPHEADER, array("Authorization: Bearer " . $accessToken));
curl_setopt($ch1, CURLOPT_RETURNTRANSFER, true);
$oUser2 = json_decode(curl_exec($ch1));
if (!isset($oUser2)) {
print "Error accessing $link_api: \n" . curl_error($ch1);
}
elseif (isset($oUser2->error)) {
}
else {
}
curl_close($ch1);
$data['loguser'] = $oUser2;
$data['data_workspace'] = $this->M_all->getLinkApi1();
$data['data_website'] = $this->M_all->getWesbiteData();
//$mymenu=new Lib_menu();
//$ret=$mymenu-> generate_menu();
//$data=array('base_url'=>$base_url,'rows_menu'=>$ret);
//print_r($data['rows_menu']['level_1']);
$data_sidebar=$this->lib_menu->sidebar_menu();
$data['koneksi'] = $this->M_all->getAllConnection();
$this->load->view('v_modultabel2', $data);
$this->load->view("sidebar.php",$data_sidebar);
break;
case "post":
$nama_tabel = $this->input->post('nama_tabel');
$nama_filter = $this->input->post('nama_filter');
$query_filter = $this->input->post('query_filter');
$kolom_tabel = $this->input->post('kolom_tabel');
$query_data = $this->input->post('queryData');
$connection_id = $this->input->post('connection_id');
if($_POST['insert_mode']==1){
$postParams = array(
'pk_tablebaru' => '',
'nama_tabel' => $nama_tabel,
'nama_filter' => $nama_filter,
'query_filter' => $query_filter,
'kolom_tabel' => $kolom_tabel,
'query_data' => $query_data,
'connection' => $connection_id,
);
$this->M_all->InsertToTableBaru('tb_tablebaru',$postParams);
$last_id = $this->M_all->getLastIDTBBaru();
$l_id = $last_id['max(pk_tablebaru)'];
$url = base_url()."viewtabel/load/$l_id";
$this->db->query("UPDATE tb_tablebaru SET url = '$url' WHERE pk_tablebaru = '$l_id'");
redirect ('/viewtabel/setting/');
}
break;
case "del":
break;
case "ambil":
$filter_data = $this->input->post('filter_data');
parse_str($filter_data, $params);
$nis = $this->session->userdata('nis');
$idmodul = $this->session->userdata('idmodul');
$dataTabel = $this->M_all->getDataTabel($idmodul);
$queryDataTabel = $dataTabel['query_data'];
$queryDataTabel=str_replace('#NIS', "'".$nis."'",$queryDataTabel);
$queryDataTabel=str_replace('#f1','"'.$params['f_1'].'"',$queryDataTabel);
$queryDataTabel=str_replace('#f2','"'.$params['f_0'].'"',$queryDataTabel);
$getDatanya = $this->M_siswa->getDatanya($queryDataTabel);
print_r($queryDataTabel);
$json_data['data'] = $getDatanya;
echo json_encode($json_data);
break;
}
}
}
?>
at the Controller, i want to get the data from database. The variables used to enter the data are $getDatanya
This is the query :
SELECT c.nama AS f1,b.nilaiangka as f2,b.nilaihuruf as f3,b.keterangan as f4 FROM tabelB b LEFT JOIN tabelC c ON c.replid = b.idpelajaran LEFT JOIN tabelA a ON b.nis = a.nis AND a.aktif = 1 WHERE b.nis = #NIS AND b.idkelas = #f1 AND b.idsemester = #f2
Hopefully I can find a solution here. Thank you very much.

How to get multiple selected values of select2 filter from datatable php serverside

I want to be able to display multiple filtering/sorting select2 from datatable and ajax php.
I have ajax.php source code, and index.php source code.
This is result table based on the code above
The Result When I fltering/sorting single data with dropdown, it’s works.
But, When I filtering/sorting with multiple select2 still doesn’t work. Data not showing.
Is there something wrong with my code? or is there a script I should add ?
Please Help me, and Thank you very much!
Index.php
// Index.php
<!DOCTYPE html>
<html>
<head>
<title>Data - Issued</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/js/select2.min.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.4/js/select2.full.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.5/css/select2.min.css" />
<link rel="stylesheet" href="https://yadcf-showcase.appspot.com/resources/css/jquery.dataTables.yadcf.0.9.2.css" />
</head>
<body class="hold-transition skin-blue sidebar-mini fixed">
<div class="wrapper">
<table class="table" style="width: 100%; font-size: 10px; margin: 20px;" class="form-horizontal" role="form">
<tr style="text-align: left;">
<td>
<div class="form-group">
<label>Name</label>
<div class="input-group">
<select id="searchByNama" name="searchByNama[]" class="form-control form-control-sm select2" multiple="multiple">
<option value="Beni">Beni</option>
<option value="Chandra">Chandra</option>
<option value="Daniel">Daniel</option>
</select>
</div>
</div>
</td>
</tr>
<tr style="text-align: left;">
<td>
<div class="form-group">
<label>Number</label>
<div class="input-group">
<select class="form-control select2" id="searchByHp">
<option selected="selected" disabled value="">Please select one</option>
<option value="021">021</option>
<option value="0838">0838</option>
<option value="0822">0822</option>
</select>
</div>
</div>
</td>
</tr>
</table>
<!-- Content Wrapper. Contains page content -->
<div class="content-wrapper" id="contentBody">
<section class="content container-fluid">
<div id="buyerPO" data-first="true" data-col-number="" data-col-name="" data-fixed="false" data-fixed2="true"></div>
<div class="box">
<div class="box-body dhg-content-list">
<div style="padding-left: 10px; padding-right: 10px;">
<table id="buyerPOList" class="table table-bordered table-hover display" style="width: 100%; font-size: 10px; white-space: nowrap; margin: auto;">
<thead>
<tr>
<th>No</th>
<th>Name</th>
<th>Number</th>
<th>Aksi</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<script type="text/javascript">
$(document).ready(function() {
const url = 'ajax.php';
const oTable = $('#buyerPOList').DataTable({
processing: true,
serverSide: true,
multiple: true,
orderable: false,
searchable: false,
ajax: {
url: url,
type: 'POST',
data: function(data) {
// Read values
var nama = $("#searchByNama").val();
var hp = $("#searchByHp").val();
// Append to data
data.searchByNama = nama;
data.searchByHp = hp;
}
},
columns: [{
data: "id"
},
{
data: "nama"
},
{
data: "no_hp"
},
{
data: "id",
"render": function(data, type, row) {
return "<a href='#' class='btn-warning btn-sm'>Edit</a> <a href='#' class='btn-danger btn-sm'>Delete</a>"
}
}
],
});
$('#searchByHp').change(function() {
oTable.draw();
});
$('#searchByNama').change(function() {
oTable.draw();
});
});
</script>
</div>
</div>
</section>
</div>
</div>
<script>
$(document).ready(function() {
$('.select2').select2()
$(document).on('collapsed.pushMenu expanded.pushMenu', function() {
hamburger()
});
});
var AdminLTEOptions = {
controlSidebarOptions: {
slide: false,
}
};
function hamburger() {
var hamburger = readCookie("hamburger");
if (hamburger == null) {
createCookie('hamburger', 'sidebar-collapse', 99999)
$('body').addClass('sidebar-collapse');
} else {
eraseCookie('hamburger');
}
}
</script>
</body>
</html>
Ajax.php
// ajax.php
<?php
include "connection.php"; // Load file koneksi.php
## Read value
$draw = $_POST['draw'];
$row = $_POST['start'];
$rowperpage = $_POST['length']; // Rows display per page
$columnIndex = $_POST['order'][0]['column']; // Column index
$columnName = $_POST['columns'][$columnIndex]['data']; // Column name
$columnSortOrder = $_POST['order'][0]['dir']; // asc or desc
$searchValue = $_POST['search']['value']; // Search value
## Custom Field value
$searchByNama = $_POST['searchByNama'];
$searchByHp = $_POST['searchByHp'];
$searchQuery = " ";
## Search
if($searchByNama != ''){
$searchQuery .= " and (nama = '".$searchByNama."' ) ";
}
// }
if($searchByHp != ''){
$searchQuery .= " and (no_hp = '".$searchByHp."') ";
}
if($searchValue != ''){
$searchQuery .= " and (
nama like '%".$searchValue."%' or
no_hp like '%".$searchValue."%' ) ";
}
## Total number of records without filtering
$sel = mysqli_query($connect,"select count(*) as allcount from tbl_kontak");
$records = mysqli_fetch_assoc($sel);
$totalRecords = $records['allcount'];
## Total number of records with filtering
$sel = mysqli_query($connect,"select count(*) as allcount from tbl_kontak WHERE 1 ".$searchQuery);
$records = mysqli_fetch_assoc($sel);
$totalRecordwithFilter = $records['allcount'];
## Fetch records
$empQuery = "select * from tbl_kontak WHERE 1 ".$searchQuery." order by ".$columnName." ".$columnSortOrder." limit ".$row.",".$rowperpage;
$empRecords = mysqli_query($connect, $empQuery);
$data = array();
while ($row = mysqli_fetch_assoc($empRecords)){
$data[] = array(
"id" =>$row['id'],
"nama" =>$row['nama'],
"no_hp" =>$row['no_hp'],
);
}
## Response
$response = array(
"draw" => intval($draw),
"iTotalRecords" => $totalRecords,
"iTotalDisplayRecords" => $totalRecordwithFilter,
"aaData" => $data
);
echo json_encode($response);
?>

How to update the database using a checkbox in a table column?

I am new to PHP and just began to learn JS as it is required at this phase of the project. I have a database named- asms
table named - filtersms
column named - filter_op . In this column of the table I have a checkbox for each row and my requirement is to enter 'yes' to the filter_op column once I check the checkbox and remains 'no' if not checked. I tried to do this using PHP itself but happens to be impossible to update the table on the click of the checkbox. As I am a beginner to JS can you please help me to get through this.
This is how filtersms table looks like,
|id |vendor |alarm_name |filter_op|
|1 |HUAWEI | communication fault |no |
|2 |HUAWEI | STP link fault |no |
|3 |ZTE | Battery discharge |no |
|4 |ZTE | AC power off |no |
Following is the PHP code I written so far to add a checkbox to each row and display the table.
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h2 mb-2 text-gray-800">Filter SMS</h1>
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h4 class="m-0 font-weight-bold text-primary">Filtered SMS Summary</h4>
</div>
<div class="card-body">
<?php
//Table select query for database
require('include/connection.php');
$query1="SELECT* FROM filtersms ";
$result_set=mysqli_query($connection,$query1);
// require('include/filtercheck.php');
?>
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</tfoot>
<tbody>
<?php
while($row=mysqli_fetch_assoc($result_set)) {
?>
<tr>
<td><?php echo $row["vendor"]; ?></td>
<td><?php echo $row["alarm_name"]; ?></td>
<td>
<form action="include/filtercheck.php" method="POST">
<div class="form-check">
<input type="checkbox" class="form-check-input" value="yes" name="filter_check" id="filter_check"/>
<label class="form-check-label" for="filter_check">Filter Alarm</label>
</div>
</form>
</td>
</tr>
<?php
}
?>
You can use jQuery.post() for it.
For each row, use:
<tr>
<td><?php echo $row["vendor"]; ?></td>
<td><?php echo $row["alarm_name"]; ?></td>
<td>
<input type="checkbox" value="2" class="js-checkbox-filter" <?php echo ($row["filter_op"] == "yes" ? "checked" : NULL) ?> />
</td>
</tr>
These checkbox are now identified by the js-checkbox-filter class, and you can use it to bind a jQuery.change() event handler on it.
var checks = $(".js-checkbox-filter")
checks.change(function() {
$.post("filtercheck.php", {
id: this.value,
filtered: this.checked ? "yes" : "no"
})
})
You'll have to change your filtercheck.php file too. It must receive an id and filtered ("yes"/"no") parameters through $_POST variable. Use them to update your database table.
You can try something like this if I understand your question correctly. That uses jQuery so you need to include the CDN script. That basically submits data via AJAX indicating the new filter options for the row checked or unchecked. It does that my posting an array as filter_op_post having index 0 = to true or false and index 1 equal to the id of the row in the database. You can process that in the filtercheck.php file, although I included a little snippet. Let me know if that works for you.
That AJAX response is in "data", so you can return whatever you want and process that as needed.
POST:
filter_op_post[] […]
0 true
1 2
RESPONSE:
["true","2"] e.g.
index.php page:
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous">
</script>
<!-- Begin Page Content -->
<div class="container-fluid">
<!-- Page Heading -->
<h1 class="h2 mb-2 text-gray-800">
Filter SMS
</h1>
<!-- DataTales Example -->
<div class="card shadow mb-4">
<div class="card-header py-3">
<h4 class="m-0 font-weight-bold text-primary">
Filtered SMS Summary
</h4>
</div>
<div class="card-body">
<?php
$Config = array(
'DB_TYPE' => 'mysql',
'DB_HOST' => '127.0.0.1',
'DB_NAME' => 'alarmfilter',
'DB_USER' => 'root',
'DB_PASS' => 'root',
'DB_PORT' => '3306',
'DB_CHARSET' => 'utf8'
);
$options = array(PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_OBJ, PDO::ATTR_ERRMODE => PDO::ERRMODE_WARNING, PDO::ATTR_EMULATE_PREPARES => true );
try {
$database = new PDO($Config['DB_TYPE'] . ':host=' . $Config['DB_HOST'] . ';dbname=' . $Config['DB_NAME'] . ';port=' . $Config['DB_PORT'] . ';charset=' . $Config['DB_CHARSET'], $Config['DB_USER'], $Config['DB_PASS'], $options);
}
catch (PDOException $e) {
// Echo custom message. Echo error code gives you some info.
echo 'Database connection can not be estabilished. Please try again later.' . '<br>';
echo 'Error code: ' . $e->getCode();
// Stop application :(
// No connection, reached limit connections etc. so no point to keep it running
exit;
}
$query="SELECT* FROM filtersms ";
$parameters = [];
$stmt = $database->prepare($query);
$stmt->execute($parameters);
$result_set = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Vendor</th>
<th>Alarm</th>
<th>Filter Option</th>
</tr>
</tfoot>
<tbody>
<?php
foreach ($result_set as $row) {
?>
<tr>
<td><?php echo $row["vendor"]; ?>
</td>
<td><?php echo $row["alarm_name"]; ?>
</td>
<td>
<form>
<div class="form-check">
<?php $checked = ($row["filter_op"] == "true")?"checked":""; ?>
<input
<?php echo $checked; ?>
type="checkbox" class="form-check-input filter_check" id ="filter_op_id
<?php echo $row["id"]; ?>
"/>
<input type="hidden" name="filter_op_post[]" value="<?php echo $row[" filter_op"]; ?>
"/>
<input type="hidden" name="filter_op_post[]" value="<?php echo $row[" id"]; ?>
"/> <label class="form-check-label" for="filter_check">Filter Alarm</label>
</div>
</form>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
<style> table, table tr, table td {
border:black 1px solid;
border-collapse: collapse;
</style>
<script>
$(".filter_check").on("click", function(e) {
$(this).next().val($(this).prop("checked"));
formdata = $(this).closest("form").serialize();
$.ajax({
type: "POST",
url: 'include/filtercheck.php',
dataType: "json",
data: formdata,
beforeSend: function(e) {
// $("#spinner").css("display", "block");
},
})
.done(function(data, textStatus, jqXHR) {
alert(data);
})
.fail(function( jqXHR, textStatus, errorThrown) {
})
.always(function(jqXHR, textStatus) {
$("#spinner").css("display", "none");
});
});
</script>
include/filtercheck.php page:
<?php
$rowid = $_POST['filter_op_post'][1];
$filter_op_value = $_POST['filter_op_post'][0];
echo json_encode($_POST['filter_op_post']);
?>
You could use a form with a submit button.
<form method="POST">
<input type="checkbox" class="form-check-input" value="true" name="filter_check" id="filter_check"/>
<label class="form-check-label" for="filter_check">
<button type="submit" name"submit" value="Submit">Submit</button>
</form>
With this you could update the database using the Post method
if(isset($_POST['submit']))
{
/* update database here
/* your value of the checkbox is &_POST['filter_check']
}

live search opetion in codeigniter with ajax

I am new to codeIgniter. want to learn this. I am facing problem. data is not populated in search page.
in model
function fetch_data($query)
{
$this->db->select('*');
$this->db->from('casedata');
if($query!='')
{
$this->db->like('status',$query);
}
$this->db->order_by('SrNo','DESC');
return $this->db->get();
}
in controller the fetch function not getting data from database
function fetch()
{
$output='';
$query='';
$this->load->model('crud_model');
if ($this->input->post('query'));
{
$query= $this->input->post('query');
}
$data=$this->Crud_model->fetch_data($query);
$output .='<div class="table-responsive">
<table class="table table_bordered table-striped
<tr>
<th>SrNo.</th>
<th>Tile</th>
<th>File No.</th>
<th>Division</th>
<th>Section</th>
<th>LDH</th>
<th>NDH</th>
<th>PDH</th>
<th>STATUS</th>
</tr>';
if($data->num_rows()>0)
{
foreach($data->result() as $row)
{
$output.='<tr> <td>'.$row->SrNo.'</td>
$output.='<tr> <td>'.$row->title.'</td>
<td>'.$row->fileno.'</td>
<td>'.$row->division.'</td>
<td>'.$row->section.'</td>
<td>'.$row->ldh.'</td>
<td>'.$row->ndh.'</td>
<td>'.$row->pdh.'</td>
<td>'.$row->status.'</td></tr>';
}
}
else{
$output.='<tr> <td colspan="5">No Data Found</td></tr> ';
}
$output.='</table>';
echo $output;
}
in view
<html>
<body>
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary" data-collapsed="0">
<div class="panel-heading">
<div class="panel-title" >
<i class="entypo-plus-circled"></i>
<?php echo get_phrase('Search Data');?>
</div>
</div>
<div class="panel-body">
<?php echo form_open(base_url() . 'index.php?
admin/student/create/' , array('class' => 'form-horizontal form-groups-
bordered validate', 'enctype' => 'multipart/form-data'));?>
<div class="form-group">
<input type="text" name="search_text" id="search_text"
placeholder="Search by Customer Detsils" class="form-control"/>
<div id="result">
</div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function()
{
load_data();
function load_data(query)
{
$.ajax({
url:"<?php echo base_url();?>index.php?
admin/fetch",method:"POST",
data:{query:query},
success:function(data){
$('#result').html(data);
}
})
}
$('#search_text').keyup(function(){
var search=(this).val();
if (search!='')
{
load_data(search);
}
else
{ load_data();
}
} );
});
</script>
Data is not populated in table. How to get output from this?
You need to loop throught the $data variable. please change the 'if' and 'foreach' as below code.
if(is_array($data) && count($data)>0)
{
foreach($data as $row)
{
still if it not working try var_dump($data) and check whether results are coming or not.

I want to pass data in codeigniter from view using ajax post, process that data in controller and send back the result array to view

I have searched the whole WWW but get nothing helpful. Any Solution will be appreciated. thanks in advance
MY HTML
<div class="row">
Either the form tag needed in my case or not
<form>
<div class="form-group">
<label for="date" class="col-12 col-md-2 control-label"><?php echo 'Date';?>
</label>
<div class="col-12 col-md-3">
<input type="text" class="datepicker form-control" name="date" id="date">
</div>
</div>
Here I am getting the data from my database
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
I am using datatable class for exporting and printing
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
<th><div><?php echo get_phrase('options');?></div></th>
</tr>
</thead>
<tbody>
<?php
$count = 1;
foreach($attendance as $row):?>
$attendance is recieved from the controller in $this->load->view('backend/index', $page_data);
<tr>
<td><?php echo $count++;?></td>
<td><?php echo $row['status'];?></td>
<td><?php echo $row['student_id'];?></td>
<td><?php echo $row['class_id'];?></td>
<td><?php echo $row['date'];?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
MY JavaScript
The script below alert() the class_id and date but do not pass anything to the controller function
<script type="text/javascript">
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {"class_id": class_id, "date": date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
}
});
}
</script>
My Controller
If I give static value to $date and $class_id as $date = '04-04-2018'; $class_id = 2; inside manage_attendance() below it works but using $this->input->post() do nothing:
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1)
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
$this->load->view('backend/index', $page_data);
}
Try to change
url: '<?php echo base_url();?>index.php?admin/manage_attendance'
to
url: '<?php echo base_url();?>index.php/admin/manage_attendance',
You have to append data like this using jquery:
function get_attendance() {
var class_id = $('#class_id').val();
var date = $('#date').val();
$.ajax({
type: "post",
dataType:"json",
data: {class_id: class_id, date: date},
url: '<?php echo base_url();?>index.php?admin/manage_attendance',
success: function (data) {
var resultData = JSON.parse(response);
if(resultData!=null){
attendance= resultData.length;
}
if(attendance>0){
for(i=0;i<attendance;i++){
$(".attendance_listing").append("<tr><td>"+resultData[i].status+"</td><td>"+resultData[i].student_id+"</td><td>"+resultData[i].class_id+"</td><td>"+resultData[i].date+"</td></tr>");
}
}
}
});
}
//controler
function manage_attendance()
{
if($this->session->userdata('admin_login')!=1){
redirect(base_url() , 'refresh');
$date = $this->input->post('date');
$class_id = $this->input->post('class_id');
$page_data['attendance']= $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
$page_data['page_name'] = 'manage_attendance';
$page_data['page_title'] = get_phrase('manage_daily_attendance');
echo json_encode($page_data);
}
}
I can get the same result by coding as following but I do not prefer that method/logic I want something as I have posted above
HTML
<div class="form-group">
<label for="class_id" class="col-12 col-md-2 control-label"><?php echo
get_phrase('Select Class');?></label>
<div class="col-12 col-md-3">
<select name="class_id" class="form-control" id="class_id" onchange="return get_attendance()" >
<option value=""><?php echo get_phrase('select class');?></option>
<?php
$classes = $this->db->get('class')->result_array();
foreach($classes as $row):?>
<option value="<?php echo $row['class_id'];?>"><?php echo $row['name'];?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</form>
</div>
<table class="table table-bordered datatable" id="table_export">
<thead>
<tr>
<th>#</th>
<th><div><?php echo get_phrase('Status');?></div></th>
<th><div><?php echo get_phrase('Student Name');?></div></th>
<th><div><?php echo get_phrase('Class Name');?></div></th>
<th><div><?php echo get_phrase('Date');?></div></th>
</tr>
</thead>
<tbody id="putdatahere">
</tbody>
</table>
JavaScript
<script type="text/javascript">
function get_attendance() {
var e = document.getElementById("class_id");
var class_id = e[e.selectedIndex].value;
var date = $('#date').val();
$.ajax({
url: '<?php echo base_url();?>index.php?admin/manage_attendance/'+ date +'/' + class_id,
success: function(response)
{
jQuery('#putdatahere').html(response);
}
});
}
</script>
CodeIgniter Controller
function manage_attendance($date, $class_id){
$query = $this->db->get_where('attendance', array('class_id' => $class_id , 'date' => $date))->result_array();
if($query){
$html_return = "";
foreach ($query as $attendance) {
$html_return .="<tr><td>";
$html_return .= $attendance['status']; //further Proccessing here e.g if $attendance['status'] == 0 echo absent otherwise present
$html_return .="</td><td>";
$html_return .= $attendance['student_id']); //further Proccessing here e.g get student name from its student_id
$html_return .="</td><td>";
$html_return .= $attendance['class_id']; //further Proccessing here e.g get class name from its class_id
$html_return .= "</td><td>";
$html_return .= $attendance['date'];
$html_return .="</td></tr>";
}
echo $html_return;
} else {
echo 'No record';
}
}

Categories