Ajax calls problems - php

I have 2 ajax calls, 1 for create and 1 for delete a folder, here is the source code
<!-- Create folder ajax -->
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('input[name="_token"]').val()
}
});
$('#create-folder').click(function(e) {
e.preventDefault();
$.ajax({
data: $('#create-folder-form').serialize(),
url: "{{ route('folders.store') }}",
type: "POST",
dataType: "json",
success: function (data) {
if(data.errors) {
alert('Sorry');
} else {
$('#create-folder-form').trigger("reset");
$('#exampleModal').modal('hide');
$('.folders').append('<li data-id=' + data.id + '>' + data.name + " <button type='button' class='btn btn-danger delete-folder' data-toggle='modal' data-id='" + data.id + "'> Delete " + "</button>" + '</li>');
}
},
error: function (data) {
console.log('Error ' + data);
}
})
});
// Delete ajax call
$('.delete-folder').click(function(e) {
let id = ($(this).data('id'));
$.ajax({
type: 'delete',
url: "folders/" + id,
success: function(data) {
$('.folders li[data-id=' + data.id + ']').remove();
}
});
});
});
</script>
index.blade.php
#extends('layouts.app')
#section('content')
<div class="container">
#include('partials.nav')
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">Folders</div>
<div class="card-body">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Create folder
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Create</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form id="create-folder-form">
#csrf
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" name="name" id="name">
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" id="create-folder">Create</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="row justify-content-center mt-3">
<div class="col-md-8">
<div class="card">
<div class="card-header">Folders</div>
<div class="card-body">
#if($folders)
<ul class="folders">
#foreach($folders as $folder)
<li data-id="{{ $folder->id }}">
{{ $folder->name }}
<button type='button' class='btn btn-danger delete-folder' data-toggle='modal' data-id='{{ $folder->id }}'>Delete</button>
</li>
#endforeach
</ul>
#endif
</div>
</div>
</div>
</div>
</div>
#endsection
Controller
public function index()
{
$user = User::findOrFail(Auth::id());
$folders = $user->folders()->get();
return view('folders.index', compact('folders'));
}
public function store(Request $request)
{
$attributes = $request->validate([
'name' => 'required'
]);
$attributes['user_id'] = Auth::id();
$folder = Folder::create($attributes);
return Response::json($folder);
}
public function destroy(Folder $folder)
{
$folder->delete();
return Response::json($folder);
}
Everything works well, it adds me the element to the DOM, but there is a little problem, when I am trying to delete a folder after i create it, it does not work, I need to refresh my page and then it is working.

Easy mistake to make. jQuery can't find the dynamically added button directly.
Instead of
$('.delete-folder').click(function(e) {...});
use
$('body').on('click','.delete-folder', function(e) {...});

Related

Pass data form controller to ajax and modal laravel 8

I tried to pass data from controller to ajax but data didnt come to my modal
This My Controller :
public function grd_checkout($paket)
{
$data= Voucher::where([
['paket',$paket],
['lokasi','GRD.NET']
])->count();
return response()->json([
'stok' => $data,
]);
}
This My Route :
Route::get('menu/grd_checkout/{paket}', [MenuController::class, 'grd_checkout']);
Button :
<td align="center" >
<button type="button" class="btn btn-primary" data-id="{{ $voucher->paket }}"
data-bs-toggle="modal" data-bs-target="#myModal">Beli
</button>
</td>
This My Form Modal :
<div class="modal fade" id="myModal" tabindex="-1" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered">
<div class="modal-content modal-sm">
<div class="modal-header">
<h5 class="modal-title" id="myModalLongTitle">Isi Data Diri dan Jumlah Pemesanan</h5>
<button type="button" class="close" data-bs-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="col-sm-6">
Stok Voucher Tersedia : <p id="stok"></p>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success">Submit</button>
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
This My Ajax :
<script>
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget)
let paket = $(this).data('id');
$.ajax({
url: '/menu/grd_checkout/' + paket,
type: 'GET',
success: function(data) {
$('#stok').text(data.stok);
}
});
});
</script>
Please kinda help to solve my error, the "stok" didnt shown up in modal, Thanks for helping!
Kindly check the response of the API and if it's okay then kindly try this:
<script>
$('#myModal').on('show.bs.modal', function (event) {
var button = $(event.relatedTarget);
let paket = $(this).data('id');
$.ajax({
url: '/menu/grd_checkout/' + paket,
type: 'GET',
success: function(data) {
$(document).find('#stok').html(data.stok);
}
});
});
</script>

My popup windows wont show even using script

i have try everything but still doesn't work. My popup windows only up until header and button but it wont show the body where all the data is in.
$(document).on('click','.delete_data',function(){
var delete_id = $(this).attr('id') ;
$.ajax ({
URL : "showbekalan.php",
type : "post",
data = {delete_id:delete_id},
success: function(data){
$("#deleteInfo").html(data);
$("#delete").modal('show');
}
});
});
<!-- Modal content-->
<td class="column100 column6" data-column="column6">
<a href="#delete" type="button" class="btn btn-danger delete_data" id="<?php echo $id ;?>" data-toggle="modal">
<font size="3">Padam</font>
</a>
</td>
<div class="modal fade" id="delete" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">
<font size="6px"><b>Padam</b></font>
</h4>
</div>
<div class="modal-body" id="deleteInfo">
<form class="contact100-form validate-form" action="deletebekalan.php?bid=<?php echo $id;?>" method="post" id="deleteForm">
<div class="container-contact100-form-btn">
<button class="contact100-form-btn" id="deleteButt">
<span>
Padam
<i class="zmdi zmdi-arrow-right m-l-8"></i>
</span>
</button>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Tutup</button>
</div>
</div>
</div>
</div>
Try to change this:
$(document).on('click','.delete_data',function(){
var delete_id = $(this).attr('id') ;
$.ajax ({
URL : "showbekalan.php",
type : "post",
data = {delete_id:delete_id},
success: function(data){
$("#deleteInfo").html(data);
$("#delete").modal('show');
}
});
});
to this:
$(document).on('click','.delete_data',function(){
var delete_id = $(this).attr('id') ;
$.ajax ({
URL : "showbekalan.php",
type : "post",
data = {delete_id:delete_id},
success: function(data){
$("#delete").modal('show');
$("#delete #deleteInfo").html(data); //Assuming that modal window has class modal
}
});
});

The GET method is not supported for this route. Supported methods: POST When Insert data

I just tried to insert data using ajax json but I'm getting a error like this. I checked in the controller, route and model. There's nothing wrong with how to set it up. Please help.
For View Blade
function add() {
save_method = 'add';
$('#form_jabatan')[0].reset(); // reset form on modals
$('#modal_form').modal('show'); // show bootstrap modal
$('[name="kode"]').prop("readonly", false);
}
function save() {
var url = "";
if (save_method === 'add') {
url = "<?php echo url('/simpanjabatan') ?>";
} else {
url = "<?php echo url('/simpanjabatan') ?>";
}
$.ajax({
url: url,
type: "POST",
data: $('#form_jabatan').serialize(),
dataType: "JSON",
success: function (data) {
if (data.errors) {
jQuery.each(data.errors, function (key, value) {
jQuery('.alert-danger').show();
jQuery('.alert-danger').append('<p>' + value + '</p>');
});
} else {
alert(data.status);
$('#modal_form').modal('hide');
reloadpage();
}
},
error: function (request, status, error) {
alert("Error json " + error);
json = $.parseJSON(request.responseText);
$.each(json.errors, function (key, value) {
$('.alert-danger').show("");
$('.alert-danger').append('<p>' + value + '</p>');
});
}
});
}
</script>
<!-- Page Content -->
<div class="content">
<h2 class="content-heading">Form Detail Jabatan</h2>
<!-- Dynamic Table Full -->
<div class="block">
<div class="block-header block-header-default">
<h3 class="block-title">DATA TABLE Detail Jabatan</h3>
</div>
<div class=" block-content block-content-full table-responsive">
<button type="button" onclick="add();" class="btn btn-primary mr-5 mb-5" data-toggle="modal">
<i class="fa fa-plus mr-5"></i>Kelola Jabatan
</button>
<div class="table-responsive">
<table id="example" class=" table table-striped js-dataTable-full-pagination ">
<thead>
<tr>
<th >ID JABATAN</th>
<th >JENIS JABATAN</th>
<th >GAJI_POKOK</th>
<th >Aksi</th>
</thead>
<tbody>
</tbody>
</table>
</div>
<!-- DataTables functionality is initialized with .js-dataTable-full-pagination class in js/pages/be_tables_datatables.min.js which was auto compiled from _es6/pages/be_tables_datatables.js -->
</div>
</div>
</div>
<!-- END Page Content -->
<!-- From Right Modal -->
<div class="modal fade" id="modal_form" tabindex="-1" role="dialog" aria-labelledby="modal-fromright"
aria-hidden="true">
<div class="modal-dialog modal-dialog-fromright" role="document">
<div class="modal-content">
<div class="block block-themed block-transparent">
<div class="block-header bg-primary-dark">
<h3 class="block-title">FORM Detail Jabatan</h3>
<div class="block-options">
<button type="button" class="btn-block-option" data-dismiss="modal" aria-label="Close">
<i class="si si-close"></i>
</button>
</div>
</div>
<div class="modal-body form">
<form action="#" id="form_jabatan" class="form-horizontal">
<input name="_token" type="hidden" id="_token" value="{{ csrf_token() }}"/>
<div class="form-body">
<div class="form-group">
{{--<label type="hidden" class="control-label col-md-3">Kode</label>--}}
<div class="col-md-9">
<input name="kode" type="hidden" class="form-control" type="text"
placeholder="Kode">
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="val-name">Jenis Jabatan</label>
<div class="col-md-9">
<select class="form-control" id="jabatan" name="jabatan">
<option value="0">Silahkan Pilih</option>
<option value="1">Ka Mantri</option>
<option value="1">Ka Mantri(baru)</option>
<option value="2">Kasir</option>
<option value="2">Staff Admin</option>
<option value="2">Mantri</option>
<option value="2">Mantri(Baru)</option>
</select>
</div>
</div>
<div class="form-group row">
<label class="col-md-3 col-form-label" for="val-name">Gaji Pokok</label>
<div class="col-md-9">
<input type="text" class="form-control" id="gaji" name="gaji"
placeholder="Masukan gaji...">
</div>
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" id="btnSave" onclick="save();" class="btn btn-primary">Save
</button>
</div>
</div>
</div>
</div>
</div>
<!-- END From Right Modal -->
For Controller
public function simpanjabatan(Request $req)
{
$obj = new DetailJabatanModel();
$obj->id_jabatan = $req->input('kode');
$obj->jabatan = $req->input('jabatan');
$obj->gaji_pokok = $req->input('gaji');
$simpan = $obj->save();
if ($simpan == 1) {
$status = "Tersmpan";
} else {
$status = "Gagal";
}
echo json_encode(array("status" => $status));
}
for route
Route::post('/simpanjabatan', 'FormJabatanController#simpanjabatan');
I want to insert with json but I got erorr:
The GET method is not supported for this route. Supported methods: POST.

Logging status of lesson to db when vimeo video complete via ajax and jquery

I am attempting to log data to my database when a vimeo video completes to in the end track students/employees time in a course as well determine when they have completed the course. I am lost when it comes to js and ajax. Below is what I have tried so far. I am using laravel 5.6.
If someone could even just point me into the right direction that would help tremendously.
#extends('layouts.app')
#section('page-title', trans('app.dashboard'))
#section('page-heading', trans('app.dashboard'))
#section('breadcrumbs')
<li class="breadcrumb-item active">
#lang('Companies')
</li>
#stop
#section('content')
#include('partials.toastr')
<div class ="row justify-content-md-center">
<div class='col-lg-6 '>
<iframe id="display" style="width:100%; height:360px;overflow:auto;" frameborder="0" webkitallowfullscreen mozallowfullscreen allowfullscreen></iframe>
</div>
</div>
<div class = "row">
<div class="col-lg-8 col-md-12">
<h2>Course Lessons</h2>
#include('courses.partials.lessons')
</div>
#permission('online.instructor.menu')
<div class="col-lg-4 col-md-12">
#include('courses.partials.instructor_menu')
</div>
<div class="modal fade" id="modalLoginForm" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header text-center">
<h4 class="modal-title w-100 font-weight-bold">Add New Lesson</h4>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body mx-3">
{!! Form::open(['route' => 'lesson.store', 'id' => 'lesson-form']) !!}
<div class="md-form mb-5">
<i class="fa fa-compass prefix grey-text"></i>
<input type="hidden" id="course_id" name="course_id" class="form-control validate" value="{{$course->id}}">
</div>
<div class="md-form mb-5">
<i class="fa fa-compass prefix grey-text"></i>
<input type="text" id="title" name="title" class="form-control validate">
<label data-error="wrong" data-success="right" for="title">Lesson Title</label>
</div>
<div class="md-form mb-5">
<i class="fa fa-sort prefix grey-text"></i>
<input type="text" id="order" name="order" class="form-control validate">
<label data-error="order" data-success="order" for="title">Number order to diplay.</label>
</div>
<div class="md-form mb-5">
<i class="fa fa-film prefix grey-text"></i>
<input type="text" id="content" name="content" class="form-control validate">
<label data-error="wrong" data-success="right" for="title">Lesson Content</label>
</div>
</div>
<div class="modal-footer d-flex justify-content-center">
<button class="btn btn-primary">Add Lesson</button>
{!! Form::close() !!}
</div>
</div>
</div>
</div>
#endpermission
</div>
#stop
#section('styles')
#stop
#section('scripts')
<script>
function onFinish() {
status.text('finished');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#form').submit(function (e) {
e.preventDefault(); //**** to prevent normal form submission and page reload
$.ajax({
type : 'POST',
url : '{{route('lesson.completed')}}',
data : {
lesson: val({{$lesson->id}}),
user: val({{$auth->user-id}}),
time: val({{date('Y-m-d h:i:s')}})
},
success: function(result){
console.log(result);
$('#head').text(result.status);
},
error: function (xhr, ajaxOptions, thrownError) {
//alert(xhr.status);
//alert(thrownError);
}
});
});
});
}
});
</script>
#stop
It appeared I had an error in my js, I rewrote the function and now have it working.
<script>
$(function() {
var iframe = $('#display')[0];
var player = $f(iframe);
var lesson_id='';
var lesson_complate_id='';
// When the player is ready, add listeners for pause, finish, and playProgress
player.addEvent('ready', function() {
player.addEvent('pause', onPause);
player.addEvent('finish', onFinish);
player.addEvent('playProgress', onPlayProgress);
});
$('button').bind('click', function() {
lesson_id=$(this).data('id');
});
function onFinish() {
console.log('finished');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
'X-Requested-With': 'XMLHttpRequest'
}
});
$.ajax({
url: '{{route('lesson.complete')}}',
method: 'POST',
data: {
lesson: lesson_id,
user: {{Auth::user()->id}},
course: {{$course->id}},
},
success: function(res){
lesson_complate_id ="#lesson_complate_id"+lesson_id;
$(lesson_complate_id).attr('class', 'badge badge-success');
$(lesson_complate_id).text('Completed')
}
});
}
</script>

How to display data from mysql in a bootstrap modal in codeigniter framework?

I am trying to fetch the product details from the database and display in a bootstrap modal. Please can someone help me.
welcome_message.php view
<div class="mix category-1 col-md-3" data-myorder="2">
<div class="product-item">
<div class="product-block">
<div class="product-block-inner">
<div class="h3">
W210 Cashew
</div>
<div class="product-image">
<img src="assets/images/Products/Whole Cashew/
W210.jpe" class="img-responsive"/>
</div>
<div class="info-inquiry">
<span class="info-button">
<INPUT TYPE="SUBMIT" NAME="INFO"
CLASS="INFO-BUTTON" VALUE="INFO / INQUIRY"
TITLE="INFO/INQUIRY"
data-toggle="modal"
data-target="#exampleModal"
data-whatever="W180" />
</span>
</div>
</div>
</div>
</div>
</div>
Modal in welcome_message.php
<div id="exampleModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"
aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body" id="modal-content">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">
Save changes</button>
</div>
</div>
</div>
</div>
Javascript:
<script>
$(document).on('show.bs.modal', '#exampleModal' ,function(event){
var button = $(event.relatedTarget) // Button that triggered the modal
var id = button.data('whatever')
var modal = $(this)
$.ajax({
url:'<?php echo base_url();?>/Welcome/ProductbyId',
data: {id:'id'},
dataType:'json',
type: "POST",
success: function(data){
var result = jQuery.parse(data);
alert(result);
$('.modal-body','#exampleModal')[0].html(result);*/
}
});
});
</script>
Welcome.php Controller
public function __construct()
{
parent::__construct();
$this->load->model('productdetail');
}
public function index()
{
$this->load->helper('url');
$this->load->view('layout/header');
$this->load->view('viewmenu.php');
$this->load->view('welcome_message');
$this->load->view('layout/footer');
}
public function ProductbyId() {
log_message('debug','Function called');
/*$productId = $_POST['id'];*/
$productId = "$_POST[id]";
$productId = 'W180';
log_message('info',$productId);
$data["results"] = $this->productdetail->ProductdetailbyId($productId);
echo json_encode($data["results"]);
}
model Productdetail.php
<?php
class productdetail extends CI_Model {
function ProductdetailbyId($id){
$condition = "Id =" . "'" . $id . "'";
$this->db->select('*');
$this->db->from('productlist');
$this->db->where($condition);
$this->db->limit(1);
$query = $this->db->get();
if ($query->num_rows() == 1){
return $query->result();
}
else {
return false;
}
}
}
?>
Please can anyone explain, how to display data from ajax call on success in bootstrap modal?

Categories