show data when dropdown change occurs in laravel - javascript

I have a data in the database with 2 table called registrations, questions i a need to show registrations table data based on questions question_schedul(considered as status)=1 or 2, In my index page there is a drop-down contains 24 hours and 15 days it related to question_schedul(status).when I select a 24 hours I need to show data corresponding to that selected status
Javascript code for dropdown
$(function () {
$("#dropselect").change(function () {
let $value;
if ($(this).val() === "24Hours") {
$value = $(this).val();
$.ajax({
type: 'GET',
url: '{{\Illuminate\Support\Facades\URL::to('tracks24or15')}}',
data: {'dropselect': $value},
success: function (data) {
$('#listdetails').html(data);
// console.log(data);
}
});
}
else {
if ($(this).val() === "15Days") {
$value = $(this).val();
$.ajax({
type: 'GET',
url: '{{\Illuminate\Support\Facades\URL::to('tracks24or15')}}',
data: {'dropselect': $value},
success: function (data) {
$('#listdetails').html(data);
// console.log(data);
});
}
else
{
alert('Select Status');
}
});
});
Index Page
<div class="content-page">
<!-- Start content -->
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="page-title-box">
<h4 class="page-title float-left">SSI TRACK</h4>
<div class="clearfix"></div>
</div>
</div>
</div>
<!-- end row -->
<div class="row">
<div class="col-12">
<div class="card-box table-responsive">
<h4 class="m-t-0 header-title"><b>SSI TRACKS</b></h4>
<div id="datatable_wrapper" class="dataTables_wrapper container-fluid dt-bootstrap4 no-footer">
<div class="row">
<div class="col-sm-6">
<select class="form-control" style="width: 150px" id="dropselect" name="dropselect">
<option>Select Status</option>
<option value="24Hours">24 Hours</option>
<option value="15Days">15 Days</option>
{{--<option value="3">All</option>--}}
</select>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<table id="datatable" class="table table-bordered dataTable table-responsive-lg">
<thead>
<tr>
<th>slno</th>
<th>Address</th>
<th>Model</th>
<th>Chassis</th>
<th>Delivery Date</th>
<th>Call</th>
</tr>
</thead>
<tbody id="listdetails">
#foreach($registeration as $registerations)
<tr>
<td class="sorting_1">{{$loop->iteration}}</td>
<td>{{$registerations->address}}</td>
<td>{{$registerations->model}}</td>
<td>{{$registerations->chassis}}</td>
<td>{{$registerations->delivery_date}}</td>
<td>
<button class="btn btn-primary btn-rounded button">Call Customer
</button>
</td>
</tr>
#endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
My Controller with function
public function tracks24or15(Request $request)
{
$register = DB::table('registrations')
->join('questions', 'registrations.registration_id', '=', 'questions.question_id')
->select('address', 'model', 'chassis', 'delivery_date')
->where([["questions.question_schedul", "=", 1] || ["questions.question_schedul", "=", 2] ])
->get();
$output = "";
$count = 1;
foreach ($register as $key => $reg) {
$output .= '<tr>' .
'<td>' . $count++ . '</td>' .
'<td>' . $reg->address . '</td>' .
'<td>' . $reg->model . '</td>' .
'<td>' . $reg->chassis . '</td>' .
'<td>' . $reg->delivery_date . '</td>' .
'<td>' . '<button>Callback</button>'. '</td>' .
// '<td>' . '..' . '<img src="assets/images/select.jpg" class="imgsize">.' . '.' . '</td>' .
'</tr>';
}
return Response($output);
}

Try changing your js
Change url
url: {{url("tracks24or15")}}
Adding datatype in ajax call
dataType: 'json',
And as both of your ajax call is same I merged into one
Javascript code for dropdown
$(function () {
$("#dropselect").change(function () {
let $value;
if (($(this).val() === "24Hours") || ($(this).val() === "15Days")) {
$value = $(this).val();
$.ajax({
type: 'GET',
url: {{url("tracks24or15")}},
data: {'dropselect': $value},
dataType: 'json',
success: function (data) {
$('#listdetails').html(data);
// console.log(data);
}
});
}
else
{
alert('Select Status');
}
});
});

Related

how to use ajax with datatable , django

i'm trying to fetching data using ajax , and display data into datatable showing data is working fine , but when i try to search or doing some sort into the datatable , it lost the data , and requires to reload the page again ?!
class MainGroup(models.Model):
admin = models.ForeignKey(User,on_delete=models.CASCADE)
main_type = models.CharField(max_length=40,unique=True)
date = models.DateTimeField(auto_now_add=True)
my views.py
def list_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
data = []
for obj in lists:
item = {
'id':obj.id,
'admin':obj.admin.username,
'main_type':obj.main_type,
'date':obj.date
}
data.append(item)
return JsonResponse({'data':data})
my templates
const form = document.getElementById('main_form')
form.addEventListener("submit",submitHandler);
function submitHandler(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '{% url 'products:maingroup' %}',
data : $('#main_form').serialize(),
dataType: 'json',
success: successFunction,
});
}
function successFunction(data) {
if (data.success) {
form.reset();
alertify.success("added")
}
else if(data.error_code=='invalid'){
for(var key in data.error_msg){
if(key == 'main_type'){
document.getElementById('main_error').removeAttribute('hidden')
document.getElementById('main_error').innerHTML = data.error_msg[key][0]
}
}
}
}
$.ajax({
type:'GET',
url:'{% url 'products:list-maingroup' %}',
success:function(response){
console.log(response)
data = response.data
var k = '<tbody>'
for(i = 0;i < data.length; i++){
k+= '<tr>';
k+= '<td>' + data[i]['id'] + '</td>';
k+= '<td>' + data[i]["admin"] + '</td>';
k+= '<td>' + data[i]["main_type"] + '</td>';
k+= '<td>' + data[i]["date"] + '</td>';
k+= '</tr>'
}
k+='</tbody>'
document.getElementById('tableData').innerHTML = k
}
})
<div class="col-md-12">
<!-- general form elements -->
<div class="card card-info">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-toggle="collapse" data-target="#main_form" aria-expanded="false" aria-controls="main_form">
<i class="fas fa-minus"></i>
</button>
</div>
<h3 class="text-center">main</h3>
</div>
<form id="main_form" role="form" method="POST">{% csrf_token %}
<div class="card-body">
<div class="form-group row">
<label for="mainGroup" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
{{form.main_type | attr:'id:mainGroup'}}
<p id="main_error" class="alert alert-danger" aria-disabled="true" hidden></p>
</div>
</div>
</div>
<!-- /.card-body -->
<div class="card-footer">
<button type="submit" class="btn btn-success">زیادکردن</button>
</div>
</form>
</div>
</div>
<div class="col-md-12">
<div class="card">
<div class="card-header">
<h3 class="text-center">infomations</h3>
</div>
<!-- /.card-header -->
<div class="card-body table-responsive">
<table id="maingroupid" class="table table-bordered table-striped text-center">
<thead>
<tr>
<th>#</th>
<th>admin</th>
<th>name</th>
<th>date</th>
</tr>
</thead>
<tbody id="tableData">
</tbody>
</tfoot>
</table>
</div>
<!-- /.card-body -->
</div>
<!-- /.card -->
</div>
<script>
$('#maingroupid').dataTable({})
</script>
and also i tried this to serialize my data
def list_maingroup(request):
lists = MainGroup.objects.all().order_by('-pk')
list_serializers = serializers.serialize('json',lists)
return HttpResponse(list_serializers,content_type='application/json')
with this ajax request
$.ajax({
type:'GET',
url:'{% url 'products:list-maingroup' %}',
success:function(data){
console.log(data)
console.log(data)
var k = '<tbody>'
for(i = 0;i < data.length; i++){
const date = new Date(data[i]["fields"]["date"]).toLocaleString();
k+= '<tr>';
k+= '<td>' + data[i]['fields']['id'] + '</td>';
k+= '<td>' + data[i]['fields']["admin"] + '</td>';
k+= '<td>' + data[i]['fields']["main_type"] + '</td>';
k+= '<td>' + date + '</td>';
k+= '</tr>'
}
k+='</tbody>'
document.getElementById('tableData').innerHTML = k
}
})
but still during using datatable search and sorting it lost the existing data , and requires to reload the page to display again!it there something i've done wrong please ?!
for those who faced this problem , i just moved $('#maingroupid').dataTable({}) to ajax call function and it works fine
thank you

ajax or jquery doesn't show data Laravel

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" />

Unable to load data on dashboard via ajax

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

Event handling in datatables when click on button as no of times that many times image opens

I am developing a program in which I use datatables, which loads dynamically with data using query and adding two buttons. It works very fine.
When I click first button an image is opened in modal. when I click same button, Image opens twice. This procedure continues as no of times I clicked on same button no of times images opens back to back.
My php code is like this:
<div class="container-fluid">
<div class="col-lg-12" style="margin-top:30px; ">
<div class="panel panel-primary">
<div class="panel-heading clickable">
<h3 class="panel-title">District Wise Sorting List TP Scheme Details</h3>
</div>
<div class="panel-body" style="overflow-x:scroll">
<table class="table table-bordered" id="tps_det">
<thead>
<tr class="success">
<th>Sr ID</th>
<th>Name</th>
<th>District</th>
<th>City</th>
<th>Button</th>
<th>Redirect</th>
</tr>
</thead>
<?php do { ?>
<tr>
<td>
<?php echo $row_Recordset1[ 'id']; ?>
</td>
<td>
<?php echo $row_Recordset1[ 'name']; ?>
</td>
<td>
<?php echo $row_Recordset1[ 'district']. "</br>" ; ?>
</td>
<td>
<?php echo $row_Recordset1[ 'city']. "</br>" ; ?>
</td>
<td>
<?php if( $row_Recordset1[ 'buttonoff']=='yes' ) { echo '<button type="button" id="'.$row_Recordset1[ 'name']. '" name="btn_'.$row_Recordset1[ 'name'].
'" onClick="funct(this);" ><img src="../data/green_circle.png" style="text-align:center;width:25px;height=25px;" /></button>'; } if( $row_Recordset1[ 'buttonoff']=='no' ) { echo '<button type="button" id="no_off" name="btn_'.$row_Recordset1[ 'name']. '" ><img src="../data/red_circle.png" style="text-align:center;width:25px;height=25px;" /></button>'; } ?>
</td>
<td>
<button type="button" id="sub" name="redirect" onClick="funct(this);">Redirect</button>
</td>
</tr>
<?php //$i++; } while ($row_Recordset1=p g_fetch_assoc($Recordset1)); ?>
</table>
</div>
</div>
</div>
</div>
in javascript procedure, I first check image is present at given source, if it presents then approproate image opens in modal and image is not present then default image is loads in modal.
My problem is that, when I click same button Image should opens only once.
How I do this.
My javascript code is like this
theTable = $('#dtble').dataTable({
"paging": true,
"lengthChange": true,
"searching": true,
"ordering": false,
"info": true,
"autoWidth": true
});
function funct(value) {
var id1 = $(value).attr('id');
var idname = $(value).attr('name');
$('#dtble tbody').on('click', 'button', function() {
var data = theTable.api().row($(this).parents('tr')).data();
var name = data[1];
var id = data[0];
if (id1 == 'sub' && idname == 'redirect') {
$.ajax({
type: "POST",
url: "../select/get_id.php",
data: 'name=' + name,
success: function(data1) {
//alert(data1);
window.location = '../index_new.php?var=' + data1 + '&name=' + name;
}
});
}
if (idname == "btn_" + name && id1 == id) {
var image_url = "../photo/" + name + ".JPG";
$.get(image_url)
.done(function() {
BootstrapDialog.show({
title: 'Name:- ' + name,
message: '<img class="image_nm" id="image_nm" src="../photo/' + name + '.JPG" height=800 width=500 style="margin-left:30px;"> '
});
}).fail(function() {
BootstrapDialog.show({
title: 'Name:- ' + name,
message: '<img class="image_nm" id="image_nm" src="../photo/default.png" height=800 width=500 style="margin-left:30px;"> '
});
});
}
});
}

How to edit and delete operation perform using jquery ajax and codeigniter

Controller Name: Product
Controller Code Below:
<?php
class Product extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper('form');
$this->load->helper('url');
$this->load->helper('html');
$this->load->model('product_model');
$this->load->library('form_validation');
}
public function test() {
$this->load->view('productlist');
}
public function add() {
$this->form_validation->set_rules('product_name', 'Product Name', 'required');
$this->form_validation->set_rules('product_category', 'Product Category', 'required');
if ($this->form_validation->run() == FALSE) {
echo validation_errors('<li>', '</li>');
} else {
$this->product_model->add($_POST);
}
}
public function displaylist() {
$result = $this->product_model->displaylist();
echo json_encode($result);
}
}
?>
Below is the view layer
View: ProductList.php
<form id="myForm" method="post" action="<?php echo site_url(); ?>/Product/add">
<div id="myModal" class="modal fade" aria-labelledby="exampleModalLabel">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="exampleModalLabel">New Product</h4>
</div>
<div class="modal-body">
<div id="message" class="text-danger"></div>
<label>Product Category:</label>
<select class="form-control" id="product_category" name="product_category" id="product_category" value="<?php echo set_value('product_category'); ?>">
<option selected="selected" value="Mobile">Mobile</option>
<option value="Computer">Computer</option>
<option value="Cloths">Cloths</option>
</select>
<label>Product Name:</label>
<input type="text" class="form-control" name="product_name" id="product_name" value="<?php echo set_value('product_name'); ?>" required="">
</div>
<div class="modal-footer">
<button type="button" name="submit" id="save_change" class="btn btn-primary" value="">Add Product</button>
<button type="button" name="cancel" id="cancel" class="btn btn-default" value="">Cancel</button>
</div>
</div>
</div>
</div>
</form>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="master"></th>
<th>Product Category</th>
<th>Product Name</th>
<th>Edit</th>
<th>Delete</th>
</tr>
</thead>
<tbody id="demo">
</tbody>
<tfoot>
<tr>
<td><button type="button" class="btn btn-danger" id="delete_data"><span class="glyphicon glyphicon-remove"></span></button>
</td>
</tr>
</tfoot>
</table>
</div>
this is javascript file so check my javascript ajax code
Javascript file Name:practice.js
var productList = {
mode: "Add",
id: "",
add: function () {
$.ajax({
url: base_url + "Product/add",
type: "POST",
data: $("#myForm").serialize(),
success: function (data) {
$('#myModal').modal('hide');
productList.list();
}
});
this.clearName();
//this.list();
},
list: function () {
$.ajax({
url: base_url + "Product/displaylist",
beforeSend: function (xhr) {
$("#demo").empty();
},
success: function (result) {
var obj = JSON.parse(result);
// console.log(obj);
var out;
var i;
for (i = 0; i < obj.length; i++) {
var category = '<tr>'
+ '<td> <input type="checkbox" class="sub_chk"> </td>'
+ '<td>' + obj[i].product_category + '</td>'
+ '<td>' + obj[i].product_name + '</td>'
+ '<td>'
+ '<a href="#" data-toggle="modal" data-target="#myModal" data-category=' + obj[i].product_category + ' data-name=' + obj[i].product_name + ' data-id= ' + obj[i].product_id + '>'
+ '<span class="glyphicon glyphicon-pencil"></span></a>'
+ '</td>'
+ '<td>'
+ '<a href="#!">'
+ '<span class="glyphicon glyphicon-trash"></span></a>'
+ '</td>'
+ '</tr>';
$("#demo").append(category);
}
}
});
},
fillData: function (name, category) {
$("#product_category").val(category);
$("#product_name").val(name);
},
clearName: function () {
$("#product_name").val('');
}
}
$(document).ready(function () {
productList.list();
productList.modal = $("#myForm");
$("#save_change").click(function () {
if (productList.mode == "Add") {
productList.add();
}
else {
productList.edit();
}
});
$("body").on('click', '.glyphicon-pencil', function () {
productList.fillData($(this).parent().data('name'), $(this).parent().data('category'));
});
});
ScreenShot for Product Table
ScreenShot for add product
MY QUESTION: How to write jquery ajax code. so check my ajax code
After to add a product you can reload the product list.
$(document).ready(function () {
productList.list();
productList.modal = $("#myForm");
$("#save_change").click(function () {
if (productList.mode == "Add") {
productList.add();
$('#demo').html('');
productList.list();
}
});
});

Categories