Modal doesn't display data fetched by axios - php

I'm new to Vue and trying to display data fetched by axios to a modal.
The problem is the modal doesn't display the data.
I've checked the birthday variable and it does contain the data.
Template
<div class="modal fade" tabindex="-1" id="birthdayModal" role="dialog">
<div class="modal-dialog modal-md modal-dialog-centered" role="document">
<div class="modal-content mx-auto text-center bg-danger text-warning">
<div class="modal-body">
<h1>
HAPPY
<i class="fa-fw fas fa-birthday-cake"></i> BIRTHDAY!
</h1>
<img
:src="'/img/members/' +birthday.dob"
width="250px"
height="250px"
class="img img-responsive"
/>
<h3 class="mt-3">{{birthday.alias_name}}</h3>
<h3>{{birthday.dob}}</h3>
</div>
</div>
</div>
</div>
Script
<script>
export default {
data() {
return {
birthday: [],
}
},
methods: {
birthdayModal() {
axios
.get('api/members/birthday')
.then(res => (this.birthday = res.data))
.then($('#birthdayModal').modal('show'))
console.log('Birthday Data: ', this.birthday)
},
},
created() {},
mounted() {
this.birthdayModal()
console.log('Component mounted.')
},
}
</script>
Controller
public function birthday()
{
$date = Carbon::now();
$member = Member::whereMonth('dob', '=', $date->month)->whereDay('dob', '=', $date->day)->get();
return $member;
}

First of all, welcome to StackOverflow HelloWorld1014!
I had a similar problem in my project, where datepicker.js wouldn't load in my modal. I resolved this by re-initializing the datepicker on modal shown event.
I did something like this:
$('#myModal').on('shown.bs.modal', function (e) {
$('.date').datepicker();
});
Hope that this can lead you in right direction.

As #ambianBeing pointed out, you don't need two .then(...). Instead, you should create another method, and call it in your first .then(...).
For example:
export default {
data(){
return{
birthday:[],
}
},
methods:{
birthdayModal(){
axios.get('api/members/birthday').then(res=>this.parseAndDisplay(res));
},
parseAndDisplay(result){
this.birthday = result.data;
$('#birthdayModal').modal('show'));
console.log("Birthday Data: ", this.birthday);
}
},
created(){
},
mounted() {
this.birthdayModal();
console.log('Component mounted.')
}
}
Hope this helps.

Related

PWA custom install

Good day all,
I have tried visiting this page: https://web.dev/customize-install/, stackover flow questions and google pages but I still cannot get it write.
I am trying to achieve three things with my PWA app:
Open "cache" and get files with the install event.
Prevent the default PWA from install using "beforeinstallprompt" listener.
Display a bootstrap modal with a "download" button.
When that button is clicked, trigger the "fetch" event which installs the app.
I am able to do 1 and 2.
I am triggering my modal on main.js. I tried in the service worker but I could not.
The download button on the modal also does not
index.php
<div class="modal fade" id="myModal3" role="dialog">
<div class="modal-dialog">
<div class="modal-content" >
<div class="modal-body">
<center><p><i class="fa fa-arrow-circle-down"></i></p>
<h5 style="margin-top:0vh;" >Download App</h5>
<p>Download our super cool app.
<div >
<div class="wrap-login100-form-btn" >
<div class="login100-form-bgbtn"></div>
<button class="login100-form-btn" class="AndaniDownload" id="btnDownloadAppOffline" >
Download </button>
</div>
</div>
</center>
</div>
</div>
</div>
</div>
Main.js
$(document).ready(function(){
$('#myModal3').modal('show');
});
pwabuilder-sw.js
importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
const CACHE = "pwabuilder-page";
const offlineFallbackPage = "offline.html";
self.addEventListener("message", (event) => {
if (event.data && event.data.type === "SKIP_WAITING") {
self.skipWaiting();
}
});
self.addEventListener('install', async (event) => {
event.waitUntil(
caches.open(CACHE)
.then((cache) => cache.add(offlineFallbackPage))
);
});
if (workbox.navigationPreload.isSupported()) {
workbox.navigationPreload.enable();
}
self.addEventListener('fetch', (event) => {
if (event.request.mode === 'navigate') {
event.respondWith((async () => {
try {
const preloadResp = await event.preloadResponse;
if (preloadResp) {
return preloadResp;
}
const networkResp = await fetch(event.request);
return networkResp;
} catch (error) {
const cache = await caches.open(CACHE);
const cachedResp = await cache.match(offlineFallbackPage);
return cachedResp;
}
})());
}
});
self.addEventListener('beforeinstallprompt', event => {
event.preventDefault();
var button =self.querySelector('.AndaniDownload');
//button.removeAttribute('hidden');
button.addEventListener('click', () => {
event.prompt();
button.setAttribute('disabled', true);
});
});

How to Fetch Data to Modal Bootstrap Using Ajax?

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

Data not being updated in CI

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 ?

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

Categories