In presented controller, it's displaying all the users and his attributes(?) such as name, surname, phone and roles. How do I make it that when I select role in checkbox and press "potvrdi"(submit) it submits to database? Do I have to use jquery, ajax?
Thank you
Controller
public function action(Request $request)
{
if ($request->ajax()) {
$query = $request->get('query');
if ($query != '') {
$data = User::where('surname', 'like', '%'.$query.'%')
->orWhere('name', 'like', '%'.$query.'%')
->orWhere('phone', 'like', '%'.$query.'%')
->orderBy('id')
->get();
} else {
$data = User::orderBy('id')
->get();
}
return json_encode($this->generateUserTable($data));
}
}
public function generateUserTable($data)
{
$total_row = $data->count();
$output = "";
if ($total_row > 0) {
foreach ($data as $row) {
$roleNames = '';
$userRoles = $row->roles()->pluck('id')->toArray();
// var_dump($userRoles);
$checked = '';
foreach (Role::all() as $roles1) {
if (in_array($roles1->id, $userRoles)) {
$checked = 'checked="checked"';
}
$roleNames .= $roles1->role != null ? $roles1->role.' '.'<input type="checkbox" '.$checked.' name="role" value="'.$roles1->id.'" class="checkbox" id="checkboxId">'.' ' : '';
}
$output .= '
<tr>
<td>'.$row->surname.'</td>
<td>'.$row->name.'</td>
<td>'.$row->phone.'</td>
<td>'.$roleNames.'</td>
<td><button type="button" id="potvrdi" class="potvrdi-button btn btn-primary" data-id="'.$row->id.'">
<div class="potvrdi">Potvrdi</div>
</button></td>
<td><button type="button" id="rowId" class="remove-button btn btn-danger" data-id="'.$row->id.'">
<div class="close">x</div>
</button></td>
</tr>
';
}
} else {
$output = '
<tr>
<td align="center" colspan="5">Nema podataka</td>
</tr>
';
}
return array(
'table_data' => $output,
'total_data' => $total_row,
);
}
EDIT:
part of html is in controller after $output in generateUserTable
view with js
<!-- Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
</div>
<div class="modal-body">
<h2>{{ $modal }}</h2>
</div>
<div class="modal-footer">
<button type="button" class="rem-mod btn btn-secondary" data-dismiss="modal">Zatvori</button>
<button type="button" class="bck-mod test btn btn-danger" data-dismiss="modal">Obriši korisnika</button>
</div>
</div>
</div>
</div>
<!-- users and search bar -->
<div class="container">
<div class="panel panel-default">
<div class="panel-heading">Pretraži korisnike</div>
<div class="panel-body">
<div class="form-group">
<input type="text" name="search" id="search" class="form-control" placeholder="Pretraži korisnike" />
</div>
<div class="table-responsive">
<h3 align="center">Broj korisnika: <span id="total_records"></span></h3>
<table id="users" class="table table-striped table-bordered">
<thead>
<tr>
<th>Prezime</th>
<th>Ime</th>
<th>Telefon</th>
<th>Rola</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
Gets data from database
<script>
$(document).ready(function(){
fetch_user_data();
function fetch_user_data(query = ''){
$.ajax({
url:"{{ route('live_search.action') }}",
method:'GET',
data:{query:query},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
$(document).on('click', '.potvrdi-button', function(){
post_user_role();
var id = $(this).data('id');
function post_user_role(id){
$.ajax({
url:"{{ route('live_search.action') }}",
method:"GET",
data:{id:id},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
}
})
$(document).on('keyup', '#search', function(){
var query = $(this).val();
fetch_user_data(query);
});
Modal js
$('#users').on('click', '.remove-button', function(){
var id = $(this).data('id');
$(".test").attr('data-id', id);
$("#deleteModal").modal("show");
});
$(document).on('click', '.bck-mod', function(){
var id = $(this).data('id');
$.ajax({
//url:"{{ route('live_search.destroy') }}",
url:"/live_search/destroy",
method:"get",
data:{id:id},
dataType:'json',
success:function(data)
{
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
},
error: function(data)
{
console.log(data);
}
})
});
});
</script>
I prepared sample fiddle for you. I used dummy values for your users table, also I used select instead of checkbox, but you should follow the same approach.
$(document).on('click', '.potvrdi-button', function(e) {
var value = $(this).closest('tr').find('select[name="role"]').val();
$.ajax({
url: "{{ route('live_search.action') }}",
method: "GET",
data: {
value: value
},
dataType: 'json',
success: function(data) {
$('tbody').html(data.table_data);
$('#total_records').text(data.total_data);
}
})
})
Check your method. Right now it's a GET. You probably want it to be a POST. Check your laravel router to make sure its responding to the POST method.
Related
I am working on old laravel project and I have to modify existing one. So I am now trying to understand the code. The project is on laravel and yajra datatable. I can't understand how the destroy function work ? In the view there is a no call for destroy function but when I click the delete button still it is working.
Controller
public function loadSizes()
{
$sizes = Size::select(['id', 'name', 'code'])->get();
return DataTables::of($sizes)
->addColumn('action', function ($size) {
return '<i class="fa fa-wrench" aria-hidden="true"></i>
<button type="button" data-id="' . $size->id . '" class="btn btn-default remove-size remove-btn" data-toggle="tooltip" data-placement="top" title="Delete"><i class="fas fa-trash-alt" aria-hidden="true"></i></button>';
})
->rawColumns(['action'])
->make(true);
}
public function destory(Request $request)
{
$result = Size::where('id', $request->input('size_id'))->delete();
if ($result) {
return "SUCCESS";
} else {
return "FAIL";
}
}
view
#extends('layouts.sidebar')
#section('content')
<div class="row">
<div class="col-sm-12 pad-main">
<div class="row">
<div class="col-md-6">
<h4 class="cat-name"> Size List</h4>
</div>
</div>
<div class="row">
<div class="col-md-12 table-responsive pad-tbl">
<table class="table table-striped" id="size_table">
<thead>
<tr>
<th scope="col"> Name</th>
<th scope="col"> Code</th>
<th scope="col"> Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
#if (Session::has('action'))
#if (Session::get('action') == "create")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size creation successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size creation fail");</script >
#endif
#elseif(Session::get('action') == "update")
#if (Session::has('status_success'))
<script > showAlert("SUCCESS", "Size update successful");</script >
#elseif(Session::has('status_error')))
<script > showAlert("FAIL", "Size update fail");</script >
#endif
#endif
#endif
<script>
$(document).ready(function () {
$('#size_table').DataTable({
language: {
searchPlaceholder: "Search records"
},
"columnDefs": [
{"className": "dt-center", "targets": "_all"}
],
processing: true,
serverSide: true,
ajax: '{!! url(' / load - sizes') !!}',
columns: [
{data: 'name', name: 'name'},
{data: 'code', name: 'code'},
{data: 'action', name: 'action'},
]
});
});
$(document.body).on("click", ".remove-size", function () {
var size_id = $(this).data('id');
showConfirm("DELETE", "Do you want to delete this Size ?", "deleteSize(" + size_id + ")");
});
function deleteSize(id) {
$.ajax({
type: 'get',
url: '{!! url('delete-size') !!}',
data: {size_id: id},
success: function (data) {
if (data == "SUCCESS") {
$('[data-id="' + id + '"]').closest('tr').remove();
showAlert("SUCCESS", "Delete Size successful");
}
}, error: function (data) {
showAlert("FAIL", "Delete Size fail");
}
});
}
</script>
#endsection
At the bottom of the blade view there is an AJAX in function destory(id).
That AJAX is sending a GET request to a URL delete-size with size id.
Now, if you search your web.php file for that URL (location - routes/web.php), you'll find something like this:
Route::get('delete-size', 'SizeController#destory');
This route would be sending the size id to your destory function, which is in turn searching the Size in your DB and deleting it.
// Controller
public function destroy($id)
{
Tag::find($id)->delete();
Toastr::success('Tag Successfully Deleted',"Success");
return redirect()->back();
}
// Route
Route::group(['as'=>'admin.','prefix'=>'admin','namespace'=>'Admin','middleware'=>['auth','admin']], function (){
Route::resource('tag','TagController');
});
// HTML file
<form id="delete-form-{{ $tag->id }}" action="{{ route('admin.tag.destroy',$tag->id) }}" method="POST" style="display: none;">
#csrf
#method('DELETE')
</form>
I have a datatable that works great. However, on the last column I have a button which should do another query and then build a second datatable, based on these results.
As you can see on the following example, when I click on the button 'searchMom' in the first row, it should run a query based on john newman´s mother('mary newman') and put the results on the panel called "Mom".
But it´s not working.
Please see the image and the code below:
View: viewFamily.blade.php
<div class="row">
<div class="col-md-12" id="rowFamily01">
<div class="panel">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
</div>
<div class="panel-title">Find a person</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-9">
<div class="form-group">
<label class="control-label" for="inputPersonSearch" >Search: </label>
<input id="inputPersonSearch" class="form-control" type="text" name="inputPersonSearch" form="formPerson">
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label class="control-label" for="btnPersonSearch" style="color: white;">Search:</label>
<button id="btnPersonSearch" class="form-control btn btn-success" type="submit" title="Search" form="formPerson">Search</button>
</div>
</div>
</div>
<div class="row" style="width:100%; margin-left: 0%;">
<div class="col-md-12 datatable" id="datatable-main">
</div>
</div>
</div>
</div>
</div>
</div>
routes: diego_routes.php
Route::group(['prefix' => 'diego', 'namespace' => 'Diego'], function () {
Route::get("/", "DiegoController#index")->name("index");
Route::get("viewFamily", "DiegoController#viewFamily")->name("viewFamily");
Route::post("searchPerson", "DiegoController#searchPerson")->name("searchPerson");
Route::get("searchMom/{mom}", "DiegoController#searchMom")->name("searchMom");
});
controller: DiegoController.php
public function searchMom($mom){
$input = $mom;
//dd($input);
//begining select query
$query = TD_CP_CIDADAO::where('CID_INT_ID_CIDADAO', '>=', "0");
if(!empty($input["filtro"])){
foreach($input["filtro"] as $k=>$v){
if(!empty($k) and !empty($v)){
//$searchValues = preg_split('/,/', $v, -1, PREG_SPLIT_NO_EMPTY);
$searchValues = array_map('trim', $v);
//dd($searchValues);
$query->where(function ($q) use ($searchValues) {
foreach ($searchValues as $value) {
$q->orWhere('CID_STR_DS_NOME', 'like', "%{$value}%");
}
});
}
}
}
//order data
if(!empty($input["order"]) and count($input["order"]) > 0)
{
foreach($input["order"] as $v){
$position = $v["column"];
$column = $input["columns"][$position]["data"];
$dir = !empty($v["dir"])? $v["dir"] : "asc";
$query->orderBy($column, $dir);
}
}
//other params...
$query->skip($input["start"])->take($input["length"]);
$json_data["data"] = $query->get()->toArray();
$json_data["recordsTotal"] = $query->count();
$json_data["recordsFiltered"] = $json_data["recordsTotal"];
$json_data["draw"] = $input["draw"];
return response()->json($json_data);
}
javascript: diego.js
$(document).on("click", ".btnMom", function(e){
e.preventDefault();
$("#newPanels").empty();
$("#newPanels").append(panelMom);
$("#datatable-mom").append(tableMom);
$("#datatable-mom").css("font-size", "12px");
if($.fn.dataTable.isDataTable('table#tbMom')){
$("table#tbMom").DataTable().destroy();
}
$.fn.dataTable.ext.errMode = 'throw';
var filtros = $(this).serializeArray().reduce(function(a, x) { a[x.name] = x.value; return a; }, {});
var options = {
serverSide: true,
processing: true,
retrieve: true,
ajax: {
dataSrc: 'data',
url : $(this).data("url"),
type: 'get',
async: false,
data: {filtro:filtros}
},
columns : columnsMom,
lengthMenu : [ 5, 10, 25 ]
};
$("table#tbMom").DataTable(options);
});
var columnsMom = [
{ data: 'CID_INT_ID_CIDADAO', visible:false},
{ data: 'CID_STR_DS_NOME'},
{ data: 'CID_DAT_DT_NASCIMENTO',
render: function(data, type, row){
return converterData(data);
}, className: "text-center"},
{ data: 'CID_STR_NM_MAE'},
{ data: 'CID_STR_NM_PAI'},
{ data: 'CID_INT_NR_RG', className: "text-center"},
{ data: 'CID_INT_NR_CPF', className: "text-center"},
{ data: 'acao',
render: function(data, type, row, meta){
var b0 = '\n\
\n\
';
return b0;
},orderable: false, className: "text-center"
}];
var panelMom =
`
<div class="panel" id="panelMom">
<div class="panel-heading">
<div class="box-tools pull-right">
<button type="button" class="btn btn-xs panel_expand"><i class="material-icons md-18">expand_less</i></button>
<button type="button" class="btn btn-xs panel_remove"><i class="material-icons md-18">close</i></button>
</div>
<div class="panel-title">Mom</div>
</div>
<div class="panel-body">
<div class="row">
<div class="col-md-12 datatable conteudod" id="datatable-mom">
</div>
</div>
</div>
</div>
`;
var tableMom =
`
<table id="tbMom" class="table table-hover compact" cellspacing="0" width="100%" >
<thead>
<tr>
<th class="hidden">ID</th>
<th>NAME</th>
<th>DOB</th>
<th>MOM</th>
<th>DAD</th>
<th class="text-center">DOC #</th>
<th class="text-center">FIELD #</th>
<th class="text-center">ACTION</th>
</tr>
</thead>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>
`;
The error message:
The line 219 (controller) shown in error message:
Results on "dd($input)" inside the controller:
I appreciate any help to solve this problem!
Thank you!
You're setting the value of $input to the value of $mom, which is the last value in your URL, so mom equals Mary Newman but the rest of your code expects $input to be an array of parameters like order, columns and start.
You should assign the value of $input as the request parameters, e.g:
public function searchMom($mom)
{
$input = request()->input();
}
Alternatively instead of $input being an array you could use the Request object directly, e.g:
public function searchMom(Request $request, $mom)
{
$request->order;
$request->columns;
$request->start;
}
I am designing CI application and is stuck in ajax query. Basically the function which i have written is taking id as null when save button is pressed even though when i click on edit button it shows its picking up the correct id. Looks like I have some error in function. BELOW IS THE FUNCTION WHICH i HAVE WRITTEN :
public function ajax_update()
{
$this->_validate();
$data = array(
//'firstName' => $this->input->post('firstName'),
//'lastName' => $this->input->post('lastName'),
//'gender' => $this->input->post('gender'),
//'address' => $this->input->post('address'),
//'dob' => $this->input->post('dob'),
//'tid' => $this->input->post('tid'),
'name' => $this->input->post('tname'),
);
$this->transport->update(array('tid' => $this->input->post('tid')), $data);
var_dump( $this->input->post());
echo json_encode(array("status" => TRUE));
}
the update function is
public function update($where, $data)
{
$this->db->update($this->table, $data, $where);
return $this->db->affected_rows();
}
View is
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
?><html lang="en">
<head>
<?php include_once("header.php"); ?>
</head>
<body class="fixed-nav sticky-footer bg-dark">
<!-- Navigation-->
<?php include_once("sidebar.php"); ?>
<div>
<div class="content-wrapper">
<div class="container-fluid">
<!-- Breadcrumbs-->
<ol class="breadcrumb">
<li class="breadcrumb-item">
Home
</li>
<li class="breadcrumb-item active">Manage Transport</li>
</ol>
<!--Button to add Client
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal2"><i class="fa fa-plus" style="color:white"></i> Add Transport</button>-->
<button class="btn btn-success" onclick="add_transport()"><i class="glyphicon glyphicon-plus"></i> Add Transport</button>
<br>
<br>
<!-- Example DataTables Card-->
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-table"></i> View Transport Details</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th style="width:90%;">Transport Detail</th>
<th>Action</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Transport Detail</th>
<th>Action</th>
</tr>
</tfoot>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<!-- /.container-fluid-->
<!-- /.content-wrapper-->
</div>
<!-- Modal to add Transport-->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">Add Transport Details</h4>
<button type="button" class="close" data-dismiss="modal">x</button>
</div>
<div class="modal-body">
<!--<form role="form" name="form1" action="<?php echo base_url('search/add_trans'); ?>" method="post" autocomplete="on">-->
<form action="#" id="form" class="form-horizontal">
<div class="row">
<div class="col-md-2">
<label>Transport Details</label>
</div>
<div class="col-md-10" id="new_data">
<textarea name="tname" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<!--<input type="submit" name="submit" class="btn btn-primary" value="Submit">-->
<button type="button" id="btnSave" onclick="save()" class="btn btn-primary">Save</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- Modal Finishes-->
</div>
<?php include_once 'footer.php'; ?>
<script type="text/javascript">
var save_method; //for save method string
var table;
//set input/textarea/select event when change value, remove class error and remove text help block
$("input").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("textarea").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
$("select").change(function(){
$(this).parent().parent().removeClass('has-error');
$(this).next().empty();
});
function add_transport()
{
save_method = 'add';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
$('#myModal').modal('show'); // show bootstrap modal
$('.modal-title').text('Add Transport'); // Set Title to Bootstrap modal title
}
function edit_transport(id)
{
//var table = $('#dataTable').DataTable();
// console.log( table.row( id ).data() );
// $("#tid").val(data.tname);
save_method = 'update';
$('#form')[0].reset(); // reset form on modals
$('.form-group').removeClass('has-error'); // clear error class
$('.help-block').empty(); // clear error string
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('transport/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
// $('[name="id"]').val(data.id);
//$('[name="tid"]').val(data.tid);
$('[name="tname"]').val(data.tname);
// $('[name="firstName"]').val(data.firstName);
//$("#tid").val(data.tname);
//alert(data.tname);
// $('[name="lastName"]').val(data.lastName);
// $('[name="gender"]').val(data.gender);
// $('[name="address"]').val(data.address);
// $('[name="dob"]').datepicker('update',data.dob);
// $('#modal_form').modal('show'); // show bootstrap modal when complete loaded
$('#myModal').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Edit Transport'); // Set title to Bootstrap modal title
// new_data
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> <input type="text" name="row_id" value="'+id+'" readonly hidden >');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
//function reload_table()
//{
// table.ajax.reload(null,false); //reload datatable ajax
//}
function reload_table() {
table.api().ajax.reload(null, false); //reload datatable ajax
}
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('transport/ajax_add')?>";
} else {
url = "<?php echo site_url('transport/ajax_update')?>";
}
// console.log($('#form').serialize());
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#myModal').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea> ');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
//$("#new_data").html('<textarea name="name" class="form-control" placeholder="Transport Name" rows="5" value=""></textarea>');
}
});
}
function delete_transport(id)
{
if(confirm('Are you sure delete this data?'))
{
// ajax delete data to database
$.ajax({
url : "<?php echo site_url('transport/ajax_delete')?>/"+id,
type: "POST",
dataType: "JSON",
success: function(data)
{
//if success reload ajax table
$('#myModal').modal('hide');
reload_table();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
function reload_table()
{
//console.log(table);
table.api().ajax.reload( null, false );
}
$(document).ready(function() {
//datatables
table = $('#dataTable').dataTable({
"processing": true, //Feature control the processing indicator.
"serverSide": true, //Feature control DataTables' server-side processing mode.
"order": [], //Initial no order.
// Load data for the table's content from an Ajax source
"ajax": {
"url": "<?php echo site_url('transport/ajax_list')?>",
"type": "POST"
},
//Set column definition initialisation properties.
"columnDefs": [
{
"targets": [ -1 ], //last column
"orderable": false, //set not orderable
},
],
});
});
</script>
</body>
</html>
Any pointers please ?
<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');}
i am trying to show ajax returned success data in bootstrap popup modal when clicking on the link.i tried but i have no idea where i have to call datatable function.
In index.php i have a modal div and ajax function to call data.php. data.php returning json encoded values.
index.php
Show Popup
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h5 class="modal-title"><i class="glyphicon glyphicon-list"></i> Stone Details</h5>
</div>
<div class="modal-body">
<div class="fetched-data">
<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
</tr>
</thead>
</table>
</div>
</div>
<div class="modal-footer">
</div>
</div>
</div>
</div>
$(document).ready(function() {
$('#myModal').on('show.bs.modal', function (e) {
var rowid = '1';
var reference = '2';
var nemix_id = '3';
$.ajax({
type : 'post',
url : 'data.php', //Here you will fetch records
data : 'rowid='+ rowid+'&reference='+reference+'&nemix_id='+nemix_id, //Pass $id
success : function(data){
$('#example').DataTable( {
"ajax": data
});
}
});
});
} );
data.php
$sql_sel = mysqli_query($con,"SELECT * FROM `table`");
$array = array();
$array['data'] = array();
while($res_sel = mysqli_fetch_row($sql_sel)){
$array['data'][] = $res_sel;
}
echo json_encode($array);
i figure it out...here i am sharing for others
var table = $('#example').DataTable( {
"ajax": {
"type" : "GET",
"url" : "data.php",
"dataSrc": function ( json ) {
return json.data;
}
}
});
If you need to show modal on load try this:
$(document).ready(function() {
// show the modal onload
$('#myModal').modal({
show: true
});
$('#myModal').on('show.bs.modal', function (e) {
var rowid = '1';
var reference = '2';
var nemix_id = '3';
$.ajax({
type : 'post',
url : 'data.php', //Here you will fetch records
data : 'rowid='+ rowid+'&reference='+reference+'&nemix_id='+nemix_id, //Pass $id
success : function(data){
$('#example').DataTable( {
"ajax": data
});
}
});
});
});