I'm trying to Ajax success message in Ajax success method, but i got Unexpected token ( error on my console by using inspect element browser.
here's my Ajax code so far :
$(document).ready(function() {
var rawDORecordsDataTable = $('#raw_do_record_table').DataTable(
{
dom: 'Blrtip',
orderCellsTop: true,
responsive: true,
processing: true,
serverSide: true,
iDisplayLength: 50,
ajax: {
url: '{{ route('raw_do_record.list') }}',
data: function(data) {
data._token = '{{ csrf_token() }}';
data.do_date = $('#search_date').val();
data.do_status = 0;
},
type: 'POST',
},
columns: [
{ data: 'do_no', name: 'do_no' },
{ data: 'do_status', name: 'do_status' },
{ data: 'customer', name: 'customer' },
{ data: 'store_isn', name: 'store_isn' },
{ data: 'warehouse_status', name: 'warehouse_status' },
{ data: 'do_date', name: 'do_date' },
{ data: 'delivery_status', name: 'delivery_status' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
] ,
searchCols: [
null ,
{ "search" : 0} ,
],
buttons: [
#if(Gate::allows('views',[[Department::LOGISTICS]]))
{ text: 'Generate All',
action: function ( e, dt, node, config ) {
$('#generate_all_modal').modal('show')
}
},
#endif
{ text: '<i class="fa fa-refresh"></i> Refresh DO',
action: function ( e, dt, node, config ) {
$('#refresh_do_modal').modal('show')
}
}
],
})
.on('click', 'a.stop', function(e) {
$.ajax({
url: '{{ route('raw_do_record.list') }}',
type: 'POST',
data: {
'_token' : '{{csrf_token() }}',
},
success: function(data) {
alert("asd");
},
error: function(data) {
alert("asdasd");
}
});
});
and here's the modal html :
<div class="modal fade bs-modal-sm" id="stop_modal" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
{{ Form::open([
'method' => 'POST',
'id' => 'stop-form'
]) }}
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true"></button>
<h4 class="modal-title">Stop Confirmation</h4>
</div>
<div class="modal-body">
<div class="form-group">
<label>Are you sure want to stop the process?<br>This DO no longer useable</label>
</div>
</div>
<div class="modal-footer">
<button class="btn sbold btn-danger" type="submit">
</i> Yes
</button>
<button type="button" class="btn sbold blue" data-dismiss="modal">No</button>
</div>
{{ Form::close() }}
</div>
</div>
any idea ?
Related
What I want to do is to input some date time range and show me the data in a BootstrapTable. I am not able to do it.
I have two php files one is my WebSite and the other is the MySql query.
So this where I load the Input data fields and my BootstrapTabel:
<div class='col-md-2 float-left'>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Datum von:</span>
</div>
<input id="dateVon" name="dateVon" value="2022-01-01" type="text" class="form-control" placeholder="2022-01-01" aria-describedby="dateVon">
</div>
</div>
<div class='col-md-2 float-left'>
<div class="input-group">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">Datum bis:</span>
</div>
<input id="dateBis" name="dateBis" value="2022-01-31" type="text" class="form-control" placeholder="2022-01-31" aria-describedby="dateBis">
</div>
</div>
</div>
<button id="remove" class="btn btn-danger btn-sm" data-toggle="modal" data-target="#deleteModal" disabled>
<i class="bi bi-trash"></i> Delete
</button>
<button id="refresh" class="btn btn-primary btn-sm" onclick="refreshFunction(dateVon,dateBis);">
<i class="bi bi-trash"></i> Refresh
</button>
</div>
<div class="card-body">
<table id="table"
data-toolbar="#table-responsive"
data-search="true"
data-show-refresh="true"
data-show-toggle="true"
data-show-fullscreen="true"
data-show-columns="true"
data-show-columns-toggle-all="true"
data-detail-view="true"
data-show-export="true"
data-click-to-select="true"
data-detail-formatter="detailFormatter"
data-minimum-count-columns="2"
data-pagination="true"
data-id-field="ID"
data-page-size="50"
data-page-list="[50, 100, all]"
data-show-footer="true"
data-side-pagination="client"
data-url="verpAnrufData.php"
data-response-handler="responseHandler"
data-detail-view="true">
</table>
<script>
var $table = $('#table')
var $remove = $('#remove')
var selections = []
function getIdSelections() {
return $.map($table.bootstrapTable('getSelections'), function(row) {
return row.ID
})
}
function responseHandler(res) {
$.each(res.rows, function(i, row) {
row.state = $.inArray(row.ID, selections) !== -1
})
return res
}
function totalTextFormatter(data) {
return 'Total'
}
function totalNameFormatter(data) {
return data.length
}
function totalPriceFormatter(data) {
var field = this.field
return '$' + data.map(function(row) {
return +row[field].substring(1)
}).reduce(function(sum, i) {
return sum + i
}, 0)
}
function initTable() {
$table.bootstrapTable('destroy').bootstrapTable({
locale: 'de-DE',
columns: [{
field: 'state',
checkbox: true,
rowspan: 1,
align: 'center',
valign: 'middle'
}, {
field: 'id',
title: 'ID',
rowspan: 1,
align: 'center',
valign: 'middle',
sortable: true,
footerFormatter: totalTextFormatter
}, {
field: 'name',
title: 'Kunde',
sortable: true,
align: 'left',
footerFormatter: totalNameFormatter
}, {
field: 'callerid',
title: 'Anrufer',
sortable: true,
align: 'left'
}, {
field: 'datetime_entry_queue',
title: 'DatumZeit',
sortable: true,
align: 'left'
}, {
field: 'duration_wait',
title: 'Warteschleife (sec)',
sortable: true,
align: 'left'
}]
})
$table.on('check.bs.table uncheck.bs.table ' +
'check-all.bs.table uncheck-all.bs.table',
function() {
$remove.prop('disabled', !$table.bootstrapTable('getSelections').length)
//$btnEdit.prop('disabled', !$table.bootstrapTable('getSelections').length)
// save your data, here just save the current page
selections = getIdSelections()
// push or splice the selections if you want to save all data selections
})
$table.on('all.bs.table', function(e, name, args) {
console.log(name, args)
})
}
$(function() {
initTable()
$('#locale').change(initTable)
})
function refreshFunction() {
var data = {
dateVon: $("input[id='dateVon']").val(),
dateBis: $("input[id='dateBis']").val()
};
$.ajax({
method: "post",
url: "verpAnrufData.php",
data: data,
success: function(response) {
/* console.log(data); */
/* params.success({
"rows": data,
"total": data.length
}, null, {}); */
//initTable();
$table.bootstrapTable('refresh')
}
})
}
and this is my MySql php file:
<?php
include "dbConn.php";
$dateVon = $_POST["dateVon"];
$dateBis = $_POST["dateBis"];
$sqltran = mysqli_query($db, "SELECT ce.id,
ce.callerid,
ce.datetime_entry_queue,
ce.duration_wait,
convert(cast(convert(cae.name using latin1) as binary) using utf8) name
FROM call_center.call_entry ce, call_center.campaign_entry cae
WHERE ce.id_campaign = cae.id
AND datetime_entry_queue BETWEEN '$dateVon 00:00:00' AND '$dateBis 23:59:59'
AND status = 'abandonada'
ORDER BY name, datetime_entry_queue ASC;");
$count = mysqli_num_rows($sqltran) ;
$arrVal = array();
$i=1;
while ($rowList = mysqli_fetch_array($sqltran)) {
$name = array(
'id' => $rowList['id'],
'name'=> $rowList['name'],
'callerid'=> $rowList['callerid'],
'datetime_entry_queue'=> $rowList['datetime_entry_queue'],
'duration_wait'=> $rowList['duration_wait'],
);
array_push($arrVal, $name);
$i++;
}
$allData = array(
'total' => $count,
'rows' => $arrVal,
);
echo json_encode($allData);
mysqli_close($db); // close connection
If i harde code the Dates in this file like this:
$dateVon = "2022-01-01";
$dateBis = "2022-12-31";
Then I can see the data, but then I am not able to input another dates and refresh it.
I am desperate I can not make it work, pls help. :)
I have found the answer of my problem, it was in the ajax function and the way I was responding the cell. Thx KIKO Software for the sugesstion.
function refreshFunction() {
$.ajax({
method: "POST",
dataType: "json",
url: "verpAnrufData.php",
data: {
dateVon: $("input[id='dateVon']").val(),
dateBis: $("input[id='dateBis']").val()
},
success: function(response) {
console.log(response);
$table.bootstrapTable('load',{
"rows": response,
"total": response.length
}, null, {});
}
})
};
I am developing a Laravel management application with Yajra datatables.
So I have various tables, and in particular in the user table I need to change the user's status (active / inactive) via ajax request by simply clicking a button or ticking a checkbox.
This is my first time using ajax and datatables, and I have no idea how to achieve this ... is it possible or are there better / quicker ways to do this?
I accept any advice or suggestion
My code:
controller
<?php
namespace Modules\User\Http\Controllers;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\User;
use DataTables;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* Display a listing of the resource.
* #return Renderable
*/
public function index(Request $request)
{
$user = User::select('id', 'name', 'email', 'attivo' , 'email_verified_at', 'created_at')->get();
if($request->ajax()){
return Datatables::of($user)
->addIndexColumn()
->addColumn('stato', function($row){
($row['attivo'] == 1 ) ? $btn1 = '<div class="btn-group" role="group" aria-label="Basic example"><a href="#" id="btn-post" dusk="postButton" class="btn btn-primary" role="button" data-toggle="modal" data-target="#addPost" style="color:white; font-size:small;">
<span class="ion-plus-circled"> Disattiva</span>
</a>'
: $btn1 = '<div class="btn-group" role="group" aria-label="Basic example"><button id="btnAttiva" class="btn btn-primary btn-rounded" style="color:white; font-size:small;">Attiva</button>';
return $btn1;
})
->addColumn('action', function($row){
$btn = '<div class="btn-group" role="group" aria-label="Basic example">View</div>';
$btn = $btn.'Edit';
$btn = $btn.'<form action="/user/delete" method="POST"><input type="hidden" name="_token" value="{{ #csrf() }}"><input type="hidden" name="_method" value="{{ #method(\'delete\') }}">
<input type="hidden" class="form-control" name="idu" value="'.$row['id'].'"><input type="submit" class="edit btn btn-danger btn-rounded" style="color:white; font-size:small;" value="Delete" /></form></div>';
return $btn;
})
->rawColumns(['action', 'stato'])
->make(true);
}
return view('user::index');
}
public function setState(Request $request){
// here i need to modify the user state
}
}
view:
#extends('layouts.master')
#section('title', 'Lista Utenti')
#section('content')
#if (\Session::has('error'))
<div class="alert alert-danger">
<ul>
<li>{!! \Session::get('error') !!}</li>
</ul>
</div>
#endif
#if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
#endif
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Utenti</h4>
<p class="card-description">
Lista degli utenti registrati
</p>
<div class="table-responsive">
<table class="table table-bordered" id="dtUserList">
<thead>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Email Verificata</th>
<th>Stato</th>
<th>Created</th>
<th>Action</th>
</thead>
</table>
</div>
</div>
</div>
</div>
<div>
<a href="{{ url('/user/create') }}" class="btn btn-primary btn-rounded"
style="color:white; font-size:small;">Aggiungi utente</a>
</div>
#endsection
#section('script')
<script>
$(function() {
var table = $('#dtUserList').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('user') }}',
columns: [
{ data: 'id', name: 'id', visible: false },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'email_verified_at', name: 'email_verified_at'},
{ data: 'stato', name: 'stato', orderable: false, searchable: false},
{ data: 'created_at', name: 'created_at' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
],
order: [[0, 'asc']]
});
});
</script>
#endsection
EDITED CODE WITH AJAX CALL:
view index.blade.php
#extends('layouts.master')
#section('title', 'Lista Utenti')
#section('content')
#if (\Session::has('error'))
<div class="alert alert-danger">
<ul>
<li>{!! \Session::get('error') !!}</li>
</ul>
</div>
#endif
#if (\Session::has('success'))
<div class="alert alert-success">
<ul>
<li>{!! \Session::get('success') !!}</li>
</ul>
</div>
#endif
<div class="col-lg-12 grid-margin stretch-card">
<div class="card">
<div class="card-body">
<h4 class="card-title">Utenti</h4>
<p class="card-description">
Lista degli utenti registrati
</p>
<div class="table-responsive">
<table class="table table-bordered" id="dtUserList">
<thead>
<th>Id</th>
<th>Name</th>
<th>Email</th>
<th>Email Verificata</th>
<th>Stato</th>
<th>Created</th>
<th>Action</th>
</thead>
</table>
</div>
</div>
</div>
</div>
<div>
<a href="{{ url('/user/create') }}" class="btn btn-primary btn-rounded"
style="color:white; font-size:small;">Aggiungi utente</a>
</div>
#endsection
#section('script')
<script type="text/javascript">
$(function() {
var table = $('#dtUserList').DataTable({
processing: true,
serverSide: true,
ajax: '{{ url('user') }}',
columns: [
{ data: 'id', name: 'id', visible: false },
{ data: 'name', name: 'name' },
{ data: 'email', name: 'email' },
{ data: 'email_verified_at', name: 'email_verified_at'},
{ data: 'stato', name: 'stato', orderable: false, searchable: false},
{ data: 'created_at', name: 'created_at' },
{ data: 'action', name: 'action', orderable: false, searchable: false },
],
order: [[0, 'asc']]
});
});
$.fn.myFunction = function(form){
//put the form elements in an array
id = $(form).serializeArray();
//Get the value of the first index(the id)
iduser = id[0]['value'];
idstato = id[1]['value'];
$.ajax({
// Post method
type: 'POST',
// Url to the route
url: "{{ url('/user/deactivate') }}",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// Data to submit to the function
data: {
//CRSF token for laravel form validations
_token: $('meta[name="csrf-token"]').attr('content'),
idu: iduser,
ids: idstato
},
success: function(response){
//if request is made successfully then the response represent the data
$( "#result" ).empty().append( response );
}
});
}
</script>
#endsection
Controller:
<?php
namespace Modules\User\Http\Controllers;
use Illuminate\Contracts\Support\Renderable;
use Illuminate\Http\Request;
use Illuminate\Routing\Controller;
use App\Models\User;
use DataTables;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
class UserController extends Controller
{
/**
* Display a listing of the resource.
* #return Renderable
*/
public function index(Request $request)
{
$user = User::select('id', 'name', 'email', 'attivo' , 'email_verified_at', 'created_at')->get();
if($request->ajax()){
return Datatables::of($user)
->addIndexColumn()
->addColumn('stato', function($row){
($row['attivo'] == 1 ) ? $btn1 = '<form><input type="hidden" name="user" value="'.$row['id'].'"><div class="form-group"><select onchange="$.fn.myFunction(this.form)" name="stato"><option value="0">Disattivo</option><option value="1" selected>Attivo</option></select></div></form>'
: $btn1 = '<form><div class="form-group"><input type="hidden" name="user" value="'.$row['id'].'"><select name="stato" onchange="$.fn.myFunction(this.form)"><option value="0" selected>Disattivo</option><option value="1">Attivo</option></select></div></form>';
return $btn1;
})
->addColumn('action', function($row){
$btn = '<div class="btn-group" role="group" aria-label="Basic example">View</div>';
$btn = $btn.'Edit';
$btn = $btn.'<form action="/user/delete" method="POST"><input type="hidden" name="_token" value="{{ #csrf() }}"><input type="hidden" name="_method" value="{{ #method(\'delete\') }}">
<input type="hidden" class="form-control" name="idu" value="'.$row['id'].'"><input type="submit" class="edit btn btn-danger btn-rounded" style="color:white; font-size:small;" value="Delete" /></form></div>';
return $btn;
})
->rawColumns(['action', 'stato'])
->make(true);
}
return view('user::index');
}
public function disattiva($idu, $ids){
dd($idu+":"+$ids);
}
}
My Route:
//rotte USER module with CRUD route
Route::middleware(['auth'])->prefix('user')->group(function() {
Route::get('/', 'UserController#index'); //dashboard -> lista utenti
Route::post('/deactivate', 'UserController#disattiva');
Route::get('/detail/{idu}', 'UserController#show'); // dettaglio specifico utente
Route::get('/edit/{idu}', 'UserController#showEditForm'); // form edit utente con dato idu
Route::patch('/edit', 'UserController#edit'); // scrivere le modifiche sul DB
Route::delete('/delete', 'UserController#destroy'); // eliminare utente dal DB
Route::get('/create', 'UserController#showCreateForm'); // form creazione nuovo utente
Route::post('/create', 'UserController#create'); // creare l'utente sul DB
Route::get('/profile', 'UserController#showProfile'); // mostra il profilo dell'utente loggato
});
Create a form inside your table and create a custom function in the select
(I assume you want to change it using a select)
<select onchange="$.fn.myFunction(this.form)">
After that you want to create a ajax request like this:
$.fn.myFunction = function(form){
//put the form elements in an array
id = $(form).serializeArray();
//Get the value of the first index(the id)
id = id[0]["value"];
$.ajax({
// Post method
type: 'POST',
// Url to the route
url: "/ajax/myfunction",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
// Data to submit to the function
data: {
//CRSF token for laravel form validations
_token: $('meta[name="csrf-token"]').attr('content'),
id: id
},
success: function(response){
//if request is made successfully then the response represent the data
$( "#result" ).empty().append( response );
}
});
}
i try to use yajra datatables laravel
i have problem in searching
when i search data already exits in datatables it no working
me already try example in documentation but it not working for me
can someone please help me?
teach me how to do like i mean
example data
example searching
** this is my javascript datatables**
let oTable = $("#example1").DataTable({
responsive: true,
autoWidth: false,
processing: true,
serverSide: true,
ajax:
{
url: '{{ route("data.user.datatables") }}',
type: 'GET',
data: function (d) {
d.filter = $('select[name=filter]').val();
}
},
columns: [
{ data: 'id'},
{ data: function(data, type, row){
return 'Username : ' + data.username +
'<br> Email : ' + data.email +
'<br> Ponsel : ' + data.contact_number;
},
name: 'username'
},
{
data: function(data, type, row){
return 'Register Date : ' + data.created_at +
'<br> Last Login : ' + data.last_login +
'<br> App By : '+ data.app_admin +' / '+ data.date_admin_app +
'<br> App By : '+ data.login +' || '+ data.status_member;
},
name: 'created_at'
},
{ data: function(data, type, row){
return 'Saldo : ' + data.saldo +
'<br> Bank Name : ' + data.bank_name +
'<br> Account Name : '+ data.account_name +
'<br> Account Number : '+ data.account_number;
},
name:'saldo'
},
{ data: 'action', orderable: false, searchable: false}
],
order:[[0,'desc']],
});
this in my Laravel CONTROLLER
if($request->ajax()):
$request->validate([
'filter' => ['string','nullable','alpha'],
]);
if($request->filled('filter')):
$users = User::query()->where('status_member', $request->filter);
else:
$users = User::query();
endif;
$data = Datatables::of($users);
$data->addIndexColumn();
$data->addColumn('action', function ($user) {
return '<div class="btn-group" role="group" aria-label="Button group with nested dropdown">
<div class="btn-group" role="group">
<button id="btnGroupDrop1" type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Action</button>
<div class="dropdown-menu" aria-labelledby="btnGroupDrop1">
<a class="dropdown-item modal-edit-user" data-toggle="modal" data-target="#modalEditUser" href="javascript:void(0)" data-id="' . $user->id . '" data-username="' . $user->username . '" >Edit</a>
<a class="dropdown-item" href="#">Dropdown link</a>
</div>
</div>
</div>';
});
$data->rawColumns(['action']);
return $data->make();
endif;
You are forwarding nothing at all to user query.
Instead of
$users = User::query()->where('status_member', $request->filter);
...
$users = User::query();
try doing
$users = User::where('status_member', $request->filter)->get();
...
$users = User::all();
EDIT:
update your code:
{ data: 'action', orderable: false, searchable: false}
to
{ data: 'action', orderable: false, searchable: true}
I was using from a Laravel project well, But today, this error appears on one of the pages:
Error: DataTables warning: table id=DataTables_table_0 - Ajax error.
For more information about this error, please see
http://datatables.net/tn/7
The recourses codes:
#extends('admin.layouts.app')
#section('title', getOption('app_name') . ' - Orders')
#section('content')
#php
$status = $status ?? false;
$dataURL = $status ? "/admin/orders-filter-ajax/$status/data" : "/admin/orders-ajax/data";
#endphp
<div class="row">
<div class="col-md-12" style="margin-bottom: 5px;">
<div class="btn-group">
<button type="button" class="btn btn-info btn-sm hide" id="apply-all">Apply</button>
</div>
<div class="btn-group">
ALL
Pending
In Progress
Completed
Partial
Refunded
Cancelled
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-default">
<div class="panel-body">
<form id="frm-apply-all" action="{{ url('/admin/orders-bulk-update') }}" method="post">
{{ csrf_field() }}
</form>
<div class="table-responsive">
<table class="table table-bordered mydatatable table-hover" style="width: 99.9%">
<thead>
<tr>
<th><input type="checkbox" class="input-sm checkbox-all"></th>
<th>#lang('general.order_id')</th>
<th>Api #lang('general.order_id')</th>
<th>#lang('general.user')</th>
<th>#lang('general.service')</th>
<th>#lang('general.package')</th>
<th>#lang('general.link')</th>
<th>#lang('general.amount')</th>
<th>#lang('general.quantity')</th>
<th>#lang('general.start_counter')</th>
<th>#lang('general.remains')</th>
<th>#lang('general.status')</th>
<th>#lang('general.date')</th>
<th class="text-center" width="5%">#lang('general.action')</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</div>
#endsection
#push('scripts')
<script>
$(function () {
$('.mydatatable').DataTable({
processing: true,
serverSide: true,
pageLength: 25,
order: [[1, 'desc']],
ajax:'{!! url($dataURL) !!}',
columns: [
{data: 'bulk', name: 'bulk', orderable: false, searchable: false},
{data: 'id', name: 'id'},
{data: 'api_order_id', name: 'api_order_id'},
{data: 'user.name', name: 'user.name'},
{data: 'package.service.name', name: 'package.service.name'},
{data: 'package.name', name: 'package.name'},
{data: 'link', name: 'link'},
{data: 'price', name: 'price', sortable: false, searchable: false},
{data: 'quantity', name: 'quantity', sortable: false, searchable: false},
{data: 'start_counter', name: 'start_counter', sortable: false, searchable: false},
{data: 'remains', name: 'remains', sortable: false, searchable: false},
{data: 'status', name: 'status'},
{data: 'created_at', name: 'created_at'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$(document).on('click', '.checkbox-all', function () {
$('.row-checkbox').trigger('click');
$('#apply-all').removeClass('hide');
});
$(document).on('click', '.row-checkbox', function () {
$('#apply-all').removeClass('hide');
var t = $(this);
if (t.is(':checked')) {
t.parents('tr').find('.row-edit').removeAttr('readonly');
t.parents('tr').attr('style', 'background-color:#dedede');
} else {
t.parents('tr').find('.row-edit').attr('readonly', 'readonly');
t.parents('tr').removeAttr('style');
}
});
$('#apply-all').on('click', function (e) {
var form = $('#frm-apply-all');
var isAnyRowSelected = false; // check if it shouldn't submit empty form
bootbox.confirm({
message: "Confirm to apply bulk update?",
buttons: {
cancel: {
label: 'Cancel',
className: 'btn-default'
},
confirm: {
label: 'Confirm',
className: 'btn-primary'
},
},
callback: function (result) {
if (result) {
// Iterate over all checkboxes in the table
$('.row-checkbox').each(function () {
var t = $(this);
if (t.is(':checked')) {
isAnyRowSelected = true; // Row selected
// Order id
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', t.attr('name'))
.val(t.val())
);
// start count
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'start_counter[' + t.val() + ']')
.val($('input[name="start_counter[' + t.val() + ']"]').val())
);
// remains
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'remains[' + t.val() + ']')
.val($('input[name="remains[' + t.val() + ']"]').val())
);
// status
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'status[' + t.val() + ']')
.val($('select[name="status[' + t.val() + ']"]').find(':selected').text())
);
}
});
if (isAnyRowSelected) {
form.submit();
}
}
}
});
});
});
</script>
#endpush
I didn't change any thing in my project today
It worked yesterday well:(
<script type="text/javascript">$('#myModal').on('show.bs.modal', function(e) { var csrf = '<?php echo csrf_token() ?>';
var $modal = $(this),
Id = e.relatedTarget.id;
var url= 'showmodal';
$.ajax({
cache: false,
type: 'post',
url: url,
data: { 'EID': Id,'_token': csrf },
success: function(data) {
alert(data);
$modal.find('.modal-body').html(data);
}
});
});</script>
controller method
public function showmodal()
{
$EID = $_POST['EID'];
$stud_details= Student::find($EID);
//return $stud_details;
return view('student.index',compact('stud_details'));
}
Route
Route::get('showmodal', 'StudentController#showmodal');
Route::post('showmodal', 'StudentController#showmodal');
view
<span class="glyphicon glyphicon-eye-open" aria-hidden="true"></span>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="myModalLabel">Student Details</h4>
</div>
<div class="modal-body">
#if ($stud_details!= '')
<table class="table table-bordered">
<tr><td>{{ Form::label('name', 'Name:') }}</td><td>{{ $stud_details->name}}</td></tr>
<tr><td>{{ Form::label('rollno', 'RollNo:') }}</td><td>{{ $stud_details->rollno}}</td></tr>
<tr><td>{{ Form::label('dept', 'Department:') }}</td><td>{{ $stud_details->department}}</td></tr>
<tr><td>{{ Form::label('course', 'Course:') }}</td><td>{{ $stud_details->course}}</td></tr>
</table>
#endif
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
i need to show the modal box with student details.but ajax post is not working.i am already return student array from index method so if i am return stud_details array it displays student is undefined.. i dont know..
you should have a different fucntion to load your view, and different one to get the data..
to retrieve your student do this:
Route:
Route::get('showmodal', 'StudentController#getStudent');
StudentController
public function getStudent()
{
$EID = $_POST['EID'];
$stud_details= Student::find($EID);
return $stud_details; //just return the value not the View
}
AJAX
$.ajax({
cache: false,
type: 'get',
url: url,
data: { 'EID': Id,'_token': csrf },
success: function(data) {
alert(data);
$modal.find('name').html(data['name']);
$modal.find('rollno').html(data['email']);
........
}
});
The idea is that you send the data back to the ajax and get every field of your modal to load each value in.
blade page use this meta code and make ajax request
<meta name="csrf-token" content="{{ csrf_token() }}">
Ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
cache: false,
type: 'post',
url: url,
data: { 'EID': Id},
success: function(data) {
alert(data);
$modal.find('name').html(data['name']);
$modal.find('rollno').html(data['email']);
........
}
if you using ajax request to controller don't use return view so change
return view
to
return json_encode('stud_details')
controller i made some changes pls refer
public function showmodal(){
$EID = $_POST['EID'];
$stud_details= Student::find($EID);
//return $stud_details;
return json_encode('stud_details');}