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.
Related
I added a search field to show live my data, but nothing works when I fill that field.
I made a route called retour.action, and that's in my controller, so when I try a console.log('test') i can see test in my Console on my browser, but the rest of the code I made doesn't work, and I also get no error
here is my controller
public function action(Request $request)
{
if ($request->ajax()) {
$output = '';
$query = $request->get('query');
if ($query != '') {
$retours = Returnorder::all()
->where('firmaname', 'like', '%' . $query . '%')
->orWhere('ordernumber', 'like', '%' . $query . '%')
->orWhere('status', 'like', '%' . $query . '%')
->get();
} else {
$retours = Returnorder::latest('id')->paginate(15);
}
$total_row = $retours->count();
if ($total_row > 0) {
foreach ($retours as $retour) {
$output .= '
<tr>
<td>' . $retour->firmaname . '</td>
<td>' . $retour->ordernumber . '</td>
<td>' . $retour->status . '</td>
</tr>
';
}
} else {
$output = '<tr>
<td align="center" colspan="5">Geen data gevonden</td>
</tr>
';
}
$retours = array(
'table_data' => $output,
);
echo json_encode($retours);
}
}
And this is my script
$(document).ready(function(){
fetch_customer_data();
function fetch_customer_data(query = '')
{
$.ajax({
url:"{{ route('retour.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(retours)
{
$('tbody').html(retours.table_data);
}
})
}
$(document).on('keypress', '#search', function(){
let query = $(this).val();
fetch_customer_data(query);
});
});
And the HTML is this
#extends('layouts.app')
#section('content')
<div class="container">
<div class="mTop">
<div class="row justify-content-center">
<div class="col-md-10">
#if(session('message'))
<div class="alert alert-success" role="alert">
{{session('message')}}
</div>
#endif
<div class="card">
<div class="card-header">Retourmeldingen</div>
<div class="card-body">
<div class="form-group" >
<label for="search" hidden>Zoeken</label>
<input type="text" name="search" id="search" class="form-control"
placeholder="Typ hier uw zoekopdracht in"/>
</div>
<table class="table table-hover">
<thead>
<tr>
<th scope="col">Firmanaam</th>
<th scope="col"></th>
<th scope="col"></th>
<th scope="col">Ordernummer</th>
<th scope="col">Status</th>
<th scope="col">Verwerkingstijd</th>
<th scope="col">Inzenddatum</th>
<th scope="col"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
#endsection
Help me please
I think you first need to be sure that what you're typing is actually being sent back to the router. You can get the value of what you're typing by using this:
$(function() {
$('#search').on('keyup', (e) => {
console.log(e.target.value);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="search" type="text" name="search" />
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);
}
I have a partial view named SIM Balance in mine dashboard. This view should show the number of sims issued to a user date wise.
I have set up the controller
public function actionSimbalance()
{
$sql = "SELECT user.`name` AS issued_to, COUNT(`sims`.`id`) AS sims_issued, sims.`operator_name` AS operator_name,
CASE
WHEN sims.`status` = 'Production Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`status` = 'Testing Stored SIM' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Zong' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
WHEN sims.`operator_name` = 'Mobilink' THEN
CAST(`sim_issueance_transaction`.`issued_at` AS DATE)
ELSE CAST(`sims`.`created_at` AS DATE) END AS issued_date
FROM `sims`
INNER JOIN `sim_issueance_transaction` ON (`sims`.`id` =
`sim_issueance_transaction`.`sim_id`)
INNER JOIN `user` ON (`sims`.`issued_to` = `user`.`id`)
WHERE sims.`status` IN ('Testing Stored SIM','Production Stored SIM')
GROUP BY user.`name`, sims.`status`, issued_date, sims.`operator_name`";
$rows = Yii::$app->db->createCommand($sql)->queryAll();
$output = [];
$grandtotal = 0;
foreach ($rows as $row) {
$std = new \stdClass();
$std->count = $row['sims_issued'];
$std->issued_to = $row['issued_to'];
$std->operator = $row['operator_name'];
$std->issued_date = $row['issued_date'];
$grandtotal += $std->count;
$output[]= $std;
}
return $this->renderPartial('sim_progress', ['model' => $output, 'grandtotal' => $grandtotal]);
}
The partial view sim_progress is below
<?php foreach ($model as $row){?>
<tr>
<td><?=$row->issued_to?></td>
<td><?=$row->count?></td>
<td><?=$row->operator?></td>
<td><?= $row->issued_date ?></td>
</tr>
<?php } ?>
<tr>
<td><strong>Grand Total</strong></td>
<td>
<strong><?= $grandtotal ?></strong>
</td>
<td></td>
</tr>
Then there is an HTML sim-balance I have designed
<div class="box box-info">
<div id="af8a8d88334">
<div class="print-header print-only">
<center><img style="width: 100px" src="<?=
\yii\helpers\Url::to('#web/images/logo.png', true); ?>"/>
</center>
<br/>
<hr/>
</div>
<div class="box-header with-border">
<h3 class="box-title">SIM Balance</h3>
</div>
<div class="box-body">
<div class="table-responsive">
<table class="table no-margin">
<thead>
<tr>
<th>Issued To</th>
<th>Sims Issued</th>
<th>Operator Name</th>
<th>Issued At</th>
</tr>
</thead>
<tbody id="dashboard-sim-balance">
</tbody>
</table>
</div>
</div>
</div>
<div class="box-footer clearfix">
<a href="javascript:void(0)" onclick="$('#af8a8d88334').printThis();"
class="btn btn-sm btn-default btn-flat pull-right">Print</a>
</div>
Then in my main site index view, I am calling it like below
.
.
.
<?php if (!Yii::$app->user->isGuest && in_array(Yii::$app->user->identity->user_role,[1,6])) {
echo $this->render('dashboard/sim-balance');
} ?>
.
.
.
.
$url_sim_balance = Url::toRoute('/dashboard/simbalance');
.
.
.
.
In my JS I am creating an ajax function which should show the details.
$script = <<< JS
$(document).ready(function () {
.
.
.
.
loadSimBalance();
.
.
.
});
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
JS;
$this->registerJs($script);
But when I run my project I cannot see the details but an empty table like below
How can I set my ajax call to view the details.
Any help would be highly appreciated.
change
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
data: data.val(), // also tried $('#dashboard-sim-balance').val()
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
To
function loadSimBalance() {
$('#dashboard-sim-balance').html('');
$.ajax({
url: '$url_sim_balance',
success:function(data) {
$('#dashboard-sim-balance').html(data);
},
error: function() {
}
});
}
am using codeigniter, am working shopping cart. after selecting of items to cart using ajax jquery. Here, items menu and cart table will be side by side displayed.
Now, my task is to copying cart items to another table, by clicking button,which is done. now problem is on clicking button i need to copied and at a time i need to route to another page.. here i can copy cart items to another table but i can't redirect to another.for this i used jquery ajax.
now i need route to page which in views folder users/basket.php
Home.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?>
<div class="row">
<div class="col-lg-12 text-center">
<?php if(isset($_SESSION['loggedin'])){?>
<div class="alert alert-success"><?php echo $_SESSION['loggedin'];?></div>
<?php } ?>
Hello, <?php echo $_SESSION['username']?>
</div>
</div>
<div class="row">
<div class="col-lg-3">
<table class="table table-condensed table-hover">
<tr>
<th class="text-center">Item</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Add</th>
</tr>
<?php foreach($items as $item):?>
<tr class="success">
<td><?php echo $item['product_name'];?></td>
<td class="text-center"><input type="text" name="quantity" id="<?php echo $item['product_id'];?>" class="quantity" maxlength="2" size="2"></td>
<td><?php echo $item['product_price'];?></td>
<td><button type="button" name="add_cart" class="add_cart" data-productname="<?php echo $item['product_name'];?>" data-price="<?php echo $item['product_price'];?>" data-productid="<?php echo $item['product_id'];?>"><i class="fa fa-plus-circle"></i></button></td>
</tr>
<?php endforeach; ?>
</table>
</div>
<div class="col-lg-6 col-lg-offset-1">
<div id="cart_details" class="text-center">
</div>
</div>
</div>
Product_controller.php:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Products extends CI_Controller {
public function add(){
$this->load->library('cart');
$data = array(
'id' => $_POST["product_id"],
'name' => $_POST["product_name"],
'qty' => $_POST["quantity"],
'price' => $_POST["product_price"],
);
$this->cart->insert($data); //return rowid
echo $this->view();
}
public function load(){
echo $this->view();
}
public function remove(){
$this->load->library('cart');
$row_id = $_POST["row_id"];
$data = array(
'rowid' => $row_id,
'qty' => 0
);
$this->cart->update($data);
echo $this->view();
}
public function clear(){
$this->load->library('cart');
$this->cart->destroy();
echo $this->view();
}
public function view(){
$this->load->library('cart');
$output = '';
$output.='
<h3>Shopping cart</h3><br/>
<div class="table-responsive">
<div align="right">
<button type="button" id="clear_cart" class="btn btn-danger"><i class="fa fa-trash-o" aria-hidden="true"></i></button>
</div>
<br/>
<table class="table table-bordered">
<tr>
<th class="text-center">Name</th>
<th class="text-center">Quantity</th>
<th class="text-center">Price</th>
<th class="text-center">Total</th>
<th class="text-center">Action</th>
</tr>';
$count = 0;
$content=$this->cart->contents();
foreach($content as $items){
$count++;
$output .='
<tr>
<td>'.$items["name"].'</td>
<td>'.$items["qty"].'</td>
<td>'.$items["price"].'</td>
<td>'.$items["subtotal"].'</td>
<td><button type="button" name="remove" class="btn btn-danger btn-xs remove_inventory" id="'.$items["rowid"].'"><i class="fa fa-times" aria-hidden="true"></i></button></td>
</tr>';
}
$output .='
<tr>
<td colspan="4" align="right">Total</td>
<td>'.$this->cart->total().'</td>
</tr>
</table>
<button type="submit" name="basket" class="btn btn-danger btn-lg basket" ><i class="fa fa-shopping-cart" aria-hidden="true"></i></button>
</div>';
if($count == 0){
$output = '<h3>Cart is Empty</h3>';
}
return $output;
}
public function basket(){
if ($cart = $this->cart->contents()){
foreach ($cart as $item){
$order_detail = array(
'tblItemsID' => $item['id'],
'tblLoginID' => $this -> session -> userdata('user_id'),
'Qty' => $item['qty'],
'price' => $item['price'],
'total' => $item['subtotal']
);
$this->db->insert('tblShoppingCart', $order_detail);
}
}
}
}
Note:In product_controller.php i coded button to copy cart items to another table. on button click event i wrote in jquery ajax below
jquery Ajax:
<script>
$(document).ready(function(){
$('.add_cart').click(function(){
var product_id=$(this).data("productid");
var product_name=$(this).data("productname");
var product_price=$(this).data("price");
var quantity=$('#' + product_id).val();
if(quantity != '' && quantity >0)
{
$.ajax({
url:"<?php echo base_url();?>products/add",
method:"POST",
data:{product_id:product_id,product_name:product_name,product_price:product_price ,quantity :quantity},
success:function(data)
{
alert("Product Added into cart");
$('#cart_details').html(data);
$('#' + product_id).val('');
}
});
}
else
{
alert("Please Enter Quantity");
}
});
$('#cart_details').load("<?php echo base_url();?>products/load");
$(document).on('click','.remove_inventory',function(){
var row_id = $(this).attr("id");
if(confirm("Are you sure you want to delete item")){
$.ajax({
url:"<?php echo base_url();?>users/remove",
method:"POST",
data:{row_id:row_id},
success:function(data)
{
alert("Product remove fromm cart");
$('#cart_details').html(data);
}
});
}else{
return false;
}
});
$(document).on('click','#clear_cart',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/clear",
success:function(data)
{
alert("Are you sure you want clear cart?");
$('#cart_details').html(data);
}
});
}
else{
return false;
}
});
$(document).on('click','.basket',function(){
if(confirm("Are you sure you want to delete item"))
{
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location="users/basket";
}
});
}
else{
return false;
}
});
});
</script>
----------
Use this code on your needed redirect place:
where you will retrieve the response via ajax success response (date);
before that you will return the value in server side which mean controller.
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
location.href = data.url_path;
}
});
Use window.location.href
$.ajax({
url:"<?php echo base_url();?>products/basket",
method:"POST",
success:function(data)
{
alert("Are you sure?");
window.location.href="<?php echo base_url();?>users/basket";
}
});
after ajax success just write.
window.location.href="redirect_location_name";
Hello I am trying to make an ajax search function in my project.
The app loads all Clients data into table on the webpage first.
and If something is typed on the searchbar,
I want searched data to be shown instead of all clients data.
I tried various ways but none of them worked out as I intended to.
Firstly I added function to check if it has any value within searchbar and if it has any value it will try to find within database and fetch data. but if it hasn't got any value it will show all client data by default.
Here is my example script code
// READ records
function readRecords() {
var searchbar = $("#search").val();
if (searchbar.val() > 0) {
$.post("ajax/search.php", {
searchbar: searchbar
}, function (data, status) {
$(".records_content").html(data);
});
} else {
$.get("ajax/readRecords.php", {}, function (data, status) {
$(".records_content").html(data);
});
}
}
Code snippet of index
<!-- Content Section -->
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Client List</h1>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="pull-xs-right">
<button class="btn btn-success" data-toggle="modal" data-target="#add_new_record_modal">Add New Client</button>
</div>
<div class="col-sm-3">
<form class="form-inline global-search" role="form" method="POST" onsubmit="readRecords()">
<div class="form-group">
<input type="text" class="form-control" id="search" placeholder="Search">
<button type="submit" id="search" class="btn btn-primary">Search</button>
</div>
</form>
</div>
</div>
</div>
<div class="row">
<div class ="col-lg-12">
<!--Where the results will be printed-->
<div class="records_content"></div>
</div>
</div>
</div>
search.php
<?php
if(isset($_POST['search']) && isset($_POST['search']) != "") {
// include Database connection file
include("SQLFunctions.php");
// Design initial table header
$data = '<table class="table table-bordered">
<tr>
<th>No.</th>
<th>Surname</th>
<th>Name</th>
<th>Address</th>
<th>Telephone</th>
<th>Inspection</th>
<th>Model</th>
<th>Serial Number</th>
<th>Notes</th>
<th>A/S Request</th>
<th>Update</th>
<th>Delete</th>
</tr>';
$search = $_POST['search'];
$searchquery = "SELECT Surname
,Name
,Address
,Telephone
,DATE_FORMAT(PurchaseDate, '%Y-%m-%d')
,Model
,SerialNumber
,Notes
FROM Clients
WHERE Surname LIKE '%".$search."%' OR Name LIKE '%".$search."%' OR Model Like '%".$search."%'";
$link = connectDB();
;
// if query results contains rows then fetch those rows
if($result = mysqli_query($link, $searchquery))
{
$number = 1;
while($row = mysqli_fetch_assoc($result))
{
$data .= '<tr>
<td>'.$number.'</td>
<td>'.$row['Surname'].'</td>
<td>'.$row['Name'].'</td>
<td>'.$row['Address'].'</td>
<td>'.$row['Telephone'].'</td>
<td>'.$row['PurchaseDate'].'</td>
<td>'.$row['Model'].'</td>
<td>'.$row['SerialNumber'].'</td>
<td>'.$row['Notes'].'</td>
<td>
<button onclick="Request('.$row['id'].')" class="btn btn-primary">A/S Request</button>
</td>
<td>
<button onclick="GetUserDetails('.$row['id'].')" class="btn btn-warning">Update</button>
</td>
<td>
<button onclick="DeleteUser('.$row['id'].')" class="btn btn-danger">Delete</button>
</td>
</tr>';
$number++;
}
}
else
{
// records now found
$data .= '<tr><td colspan="6">Records not found!</td></tr>';
}
$data .= '</table>';
echo $data;
}
?>
When I run this project, everything work properly but When I enter any value into searchbar it gives same all results of clients.
I am trying to figure out which is the best way to make this function functioning. Any tips would be appreciated thank you in advance
Prevent the default submit event
onsubmit="readRecords(this)"
function readRecords(e) {
e.preventDefault();
var searchbar = $("#search").val();
if (searchbar.val() > 0) {
$.post("ajax/search.php", {
searchbar: searchbar
}, function (data, status) {
$(".records_content").html(data);
});
} else {
$.get("ajax/readRecords.php", {}, function (data, status) {
$(".records_content").html(data);
});
}
}
use event.preventDefault() method of jquery before calling the ajax request.
If this method is called, the default action of the event will not be triggered.