<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');}
Related
I am trying to take amount from the html tags and store the amount into database but the about here
ajax code is not working and data is not stored in the database. And how to know if ajax code is redirected it's control to the laravel controller
#include('layouts.students.header')
<meta name="csrf-token" content="{{csrf_token()}}">
<body>
<div class="col">
<p class="text-right" style="font-size: 18px;">
<i class="fa fa-rupee"></i><strong
class="amount">299</strong>
</p>
</div>
<div class="form-group text-right">
<button class="btn btn-warning btn-block btn-lg
buy_now">Proceed</button>
</div>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('button').click(function(event){
e.preventDefault();
var amount = $('.amount').html();
$.ajax({
url : '{{route('razorpay')}}',
method : 'POST',
dataType : 'jason',
data : {amount :amount * 100},
success : function (Response) {
console.log(Response);
}
});
});
});
</script>
</body>
</html>
controller :
public function dopayment(Request $request)
{
$data = $request->all();
$result = Payment::insert($data);
echo "inserted";
}
In ajax method can you use dataType : 'json', instead of jason
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;
}
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.
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 ?
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
});
}
});
});
});