How to Fetch Data to Modal Bootstrap Using Ajax? - php

I have one page that display list of the item from databse. I want to open the item detail with bootstrap modal through jquery. I know ajax in running to success as it throws alerts. But cannot open modal.
Can you please show me the wrong code ? thank you
These are my code :
This is the Model
function get_detail_item($id){
$this->db->select('*');
$this->db->from('item', 'purchase');
$this->db->join('purchase', 'purchase.id=item.id_purchase', 'inner');
$this->db->join('status', 'status.id=item.id_status', 'inner');
$this->db->join('category', 'category.id=item.id_category', 'inner');
$this->db->where('item.id', $id);
$query = $this->db->get();
return $query->row();
}
This is the Controller
function detail_item($id){
$this->load->model('item_model');
$data = $this->item_model->get_detail_item($id);
echo json_encode($data);
}
This is the Button
Detail
This is the Modal
<div class="modal fade" id="Item_Detail" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Detail Item</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<p id="proName"></p>
<p id="proRoom"></p>
<p id="proBuilding"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
This is the Ajax
<script type="text/javascript">
$('#Item_Detail').on('show.bs.modal', function (e) {
var productID= $(e.relatedTarget).data('id');
$.ajax({
url:"<?php echo base_url().'admin/detail_item/'?>/" + productID,
method: "GET",
dataType:"JSON",
success:function(data)
{
$('#proName').val(data.name_item);
$('#proRoom').val(data.room);
$('#proBuilding').val(data.building);
}
})
});

Try it with this code for your model:
function get_detail_item($id){
//I do not know if you will have get conflicts with select columns because of the same names
$this->db->join('purchase', 'purchase.id=item.id_purchase', 'inner');
$this->db->join('status', 'status.id=item.id_status', 'inner');
$this->db->join('category', 'category.id=item.id_category', 'inner');
$this->db->where('item.id', $id);
$query = $this->db->get('item');
return $query->row_array();
}
The button:
Detail
Please, the controller keeps with echo and json_encode. And the ajax call, like that:
//It good practice to use a delegate event, but you choose it
$('.js-detail').on('click', function(){
var id = $(this).data('id');
console.log("ID: " +id);
$.ajax({
type: 'GET',
url: '/admin/detail_item/'+id,
success:function(data)
{
var result = JSON.parse(data);
console.log(result);
$('#proName').text(result.name_item);
$('#proRoom').text(result.room);
$('#proBuilding').text(result.building);
$('#Item_Detail').modal('show');
}
error: function (data) {
alert("error");
}
});
});
Please, see the console log to results ajax and possible errors during execution.

Write this on success
success:function(data)
{
$('#Item_Detail').modal('show')
$('#proName').text('').text(data.name_item);
$('#proRoom').text('').text(data.room);
$('#proBuilding').text('').text(data.building);
}
and change function return not echo
function detail_item($id){
$this->load->model('item_model');
$data = $this->item_model->get_detail_item($id);
return $data;
}

Related

Changing roles on admin panel in checkbox

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.

How to pass view data to Controller by CodeIgniter using ajax Code?

I have a problem to delet the row data from a page. After clicking "OK" buttton nothing would be appear.
<td><a id ="mybutton" data-toggle="modal" data-target="#confirm_delete_button" data-id="<?php echo $row -> id?>" href="" ><i class="glyphicon glyphicon-remove"></i></a>
The modal is
<div class="modal fade" id="confirm_delete_button" role="dialog" aria-labelleby="myModalLabel" aria-hidden="true" z-index: 1050;>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h class="modal-title" id="myModalLabel">Delet this data</h>
</div>
<div class="modal-body">
<h4>Are you sure? </h4>
<div id="done"></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="confirmOk">Ok</button>
<button type="button" class="btn btn-success" data-dismiss="modal" aria-hidden="true">Cancel</button>
</div>
</div>
</div>
</div>
The JQuery code is
<script type="text/javascript">
$(document).ready(function(){
$('#mybutton').click(function(){
var id = $(this).data('id');
$('#confirmOk').data('id',id);
});
$('#confirmOk').click(function(){
var id = $(this).data('id');
$.ajax {
url : "<?php echo base_url();?>item_list/delete_item/",
type : "post" ,
data : {"id":id},
dataType:"json",
success : function (data) {
$('#confirm_delete_button').modal('hide');
}
}
});
});
</script>
The function of controller file item_list.php file is
public function delete_item () {
//$id = $this->uri->segment(3);
$id=$this->input->post('id');
$this -> item_list_model -> delete_item ($id);
echo $id;
}
The item_list_model.php file is
public function delete_item ($id) {
return $this -> db -> query ("DELETE FROM item WHERE id='$id' ");
}
The output is The "OK" button does not delet the row
Actually your ajax post endpoint into controller should return some response using echo + json enconde. In that way your success callback into ajax jquery call can catch it and continue the flow correctly (hiding modal).
JQuery Ajax POST in Codeigniter
Try out below code
Controller
public function delete_item () {
//$id = $this->uri->segment(3);
$id=$this->input->post('id');
$result = $this->item_list_model->delete_item ($id);
if($result > 0 ){
echo "success";
}else{
echo "failure";
}
}
Model
public function delete_item ($id) {
$this->db->where('id', $id);
$this->db->delete('item');
return $this->db->affected_rows();
}
ajax
success : function (data) {
//$('#confirm_delete_button').modal('hide');
alert(data);
}
try changing data : {"id":id}, into data : {id:id}, maybe the data id didn't sent correctnly in the controller thats why it's not working.

Send Data Ajax to Controller and assign to modal box [laravel]

<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');}

Show ajax success data in bootstrap modal as datatable

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

CodeIgniter Update query not working

I want to terminate a employee from the system. When clicks on terminate button it will popup a moadal asking whether wants to terminate or cancel. If terminate database value resign should be updated as 0, but right now button does not working.
Here is my code
controller
public function ajax_list()
{
$list = $this->employees->get_datatables();
$data = array();
$no = $_POST['start'];
foreach ($list as $emp) {
$no++;
$row = array();
$row[] = $emp->employee_id;
$row[] = $emp->name;
$jid = $emp->job_title;
$desigdata = $this->employees->GetJobTitlebyID($jid);
$row[] = $desigdata->desc;
$did = $emp->department;
$deptdata = $this->employees->GetDepartmentbyID($did);
$row[] = $deptdata->title;
$secid = $emp->section;
$secdata = $this->employees->GetSectionbyID($secid);
$row[] = $secdata->desc;
//add html for action
$row[] = '<a class="btn btn-sm btn-primary" href="javascript:void()" onclick="terminate_emp('."'".$emp->id."'".')"><i class="glyphicon glyphicon-pencil"></i> Terminate</a>';
$data[] = $row;
}
$output = array(
"draw" => $_POST['draw'],
"recordsTotal" => $this->employees->count_all(),
"recordsFiltered" => $this->employees->count_filtered(),
"data" => $data,
);
echo json_encode($output);
}
public function ajax_terminate()
{
$this->_validate();
$data = array(
'resign' => $this->input->post('resign'),
);
$this->employees->update(array('id' => $this->input->post('id')), $data);
echo json_encode(array("status" => TRUE, "id" => $this->input->post('id')));
}
Model
function terminate_emp($data)
{
$this->db->where('resign', 0);
$this->db->update('employees', $data);
}
View
function terminate_emp(id)
{
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error');
$('.help-block').empty();
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('employees_con/ajax_terminate/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
if(data.resign == 1)
{
//$('[name="resign"]').val(data.resign);
$('#resign').prop('checked', true);
}
$('[name="resign"]').val(data.resign);
$('#modal_formterminate').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Terminate Employee'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
<div class="modal fade" id="modal_formterminate" role="dialog">
<div class="modal-dialog modal-full" style="max-width: 600px">
<div class="modal-content">
<div class="modal-header bg-blue-steel bg-font-blue-steel">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h3 class="modal-title bold uppercase">Person</h3>
</div>
<div class="modal-body form">
<form action="#" id="form" class="form-horizontal">
<input type="hidden" value="" name="id"/>
<div class="form-body">
<div id="empWizard">
<p style="color: #0000cc"><b>Are You sure to Terminate this employee</b></p>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSaveterminate" onclick="save()" class="btn btn-primary">Terminate</button>
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancel</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
In controller
$this->employees->update(array('id' => $this->input->post('id')), $data);
You are passing two parameters to update function of your model, one is an array and the other one $data that is also an array.
But In Model,
function terminate_emp($data)
{
$this->db->where('resign', 0);
$this->db->update('employees', $data);
}
you are just accepting one parameter in the update function.
First of all you are making GET request through AJAX and on Controller function ajax_terminate() you are accessing variables using POST. You resign value is not passing through ajax and you are trying to get on controller function ajax_terminate(). See below code:-
function terminate_emp(id)
{
save_method = 'update';
$('#form')[0].reset();
$('.form-group').removeClass('has-error');
$('.help-block').empty();
//Ajax Load data from ajax
$.ajax({
url : "<?php echo site_url('employees_con/ajax_terminate/')?>/",
type: "POST",
dataType: "JSON",
data: {id:id,resign:YOUR_RESIGN_VALUE}
success: function(data)
{
$('[name="id"]').val(data.id);
if(data.resign == 1)
{
//$('[name="resign"]').val(data.resign);
$('#resign').prop('checked', true);
}
$('[name="resign"]').val(data.resign);
$('#modal_formterminate').modal('show'); // show bootstrap modal when complete loaded
$('.modal-title').text('Terminate Employee'); // Set title to Bootstrap modal title
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
Change Model to
function terminate_emp($where,$data)
{
$this->db->where($where);
$this->db->update('employees', $data);
}

Categories