Datatables are not updated when opening modals via datatables column hyperlinks - ajax

I have a problem here.
Here there are 2 Datatables, 1 to display the initial data, and 1 to display one of the data from the first table. I am using Name column as Hyperlink using href. When the name is clicked, modals appear containing details. When I press another name, the datatables in the modals are not updated, only the data with the first name appears.
Here's the code
<form id="filter-form">
<div class="row">
<div class="col-md-3 col-sm-6 mb-3">
<label for="">Tahun</label>
<select class="form-control" id="f_tahun" name="f_tahun">
<option value=''> Pilih Tahun </option>
<? foreach ($tahun as $row) : ?>
<option value='<? echo $row['f1']; ?>'><? echo $row['f1']; ?></option>
<? endforeach; ?>
</select>
</div>
<div class="col-md-3 col-sm-6 mb-3">
<label for="">Bulan</label>
<select class="form-control" id="f_bulan" name="f_bulan">
<option value=''> Pilih Bulan </option>
</select>
</div>
<div class="col-md-3 col-sm-6 mb-3">
<label for="">Departemen</label>
<select class="form-control" id="f_depart" name="f_depart">
<option value=''> Pilih Departemen </option>
<? foreach ($depart as $row) : ?>
<option value='<? echo $row['f2']; ?>'><? echo $row['f2']; ?></option>
<? endforeach; ?>
</select>
</div>
<div class="col-md-3 col-sm-6 mb-3">
<label for="">Kelas</label>
<select class="form-control" id="f_kelas" name="f_kelas">
<option value=''> Pilih Kelas </option>
</select>
</div>
<br>
</div>
<div style="margin-top:20px;">
<input type="submit" name="submit" value="Filter" class="btn btn-primary d-inline">
</div>
</form>
<div class="row">
<div class="col-md-12">
<br>
<div class="table-responsive">
<table class="table table-bordered" id="example" style="width:100%;">
<thead>
<tr>
<th>Nama</th>
<th>Hadir</th>
<th>Izin</th>
<th>Sakit</th>
<th>Cuti</th>
<th>Alpa</th>
<th>Total</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
Here's a Modals
<div class="modal fade" id="myModal" style="display:none">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
</div>
<div class="modal-body">
<table id="modal_table" class="table table-striped">
<thead>
<tr>
<th>Tanggal</th>
<th>Hadir</th>
<th>Ijin</th>
<th>Sakit</th>
<th>Cuti</th>
<th>Alpa</th>
</tr>
</thead>
</table>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default " data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
Here's the Javascript
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.25/js/jquery.dataTables.min.js"></script>
<script>
$(document).ready(function() {
var dataTable;
var tahun = document.getElementById("f_tahun").value;
var bulan = document.getElementById("f_bulan").value;
dataTable = $('#example').DataTable({
"ajax": {
url : "<? echo base_url('absenSiswa/getAbsen'); ?>",
type: "POST",
data: {filter_data : function(){ return $('#filter-form').serialize();}}
},
"columnDefs": [{
"defaultContent": "-",
"targets": "_all"
}],
"aoColumns": [
{data : "nama",
render: function (data, type, row) {
return ''+data+'';
}},
{data : "hadir"},
{data : "ijin"},
{data : "sakit"},
{data : "cuti"},
{data : "alpa"},
{data : "total"}
],
"scrollCollapse": true,
"fixedColumns": {
"left": 1
},
"scrollX": true,
'processing': true,
'language': {
"loadingRecords": ' ',
"processing" : '<i class="fa fa-spinner fa-spin" style="font-size:24px;color:rgb(75, 183, 245);"></i>'
},
});
$('#filter-form').submit(function(e){
e.preventDefault();
dataTable.ajax.reload();
})
});
</script>
<script>
function launch(nis){
document.getElementById('myModal').style.display='';
alert(nis);
var dataTable1;
var tahun = document.getElementById("f_tahun").value;
var bulan = document.getElementById("f_bulan").value;
dataTable1 = $('#modal_table').DataTable({
"ajax": {
url : "<? echo base_url('absenSiswa/getDetail'); ?>",
type: "POST",
data: {filter_data : function(){ return $('#filter-form').serialize();},
nis : function(){return nis;}}
},
"columnDefs": [{
"defaultContent": "-",
"targets": "_all"
}],
"aoColumns": [
{data : "tanggal"},
{data : "hadir"},
{data : "ijin"},
{data : "sakit"},
{data : "cuti"},
{data : "alpa"}
],
"scrollCollapse": true,
"fixedColumns": {
"left": 1
},
"scrollX": true,
'processing': true,
'language': {
"loadingRecords": ' ',
"processing" : '<i class="fa fa-spinner fa-spin" style="font-size:24px;color:rgb(75, 183, 245);"></i>'
},
});
}
</script>
Thank you very much

Related

Laravel 9 uploading to storage and using image for new blog post

Blog post
Above is my blog post, Below I will post my current set up.
New blog form
I'm new to this so, I want to be able to upload images and each of my blog post to pull the requested images. Currently the file selector isn't linked so it creates a fake path.
This is my blogs controller
<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use App\Http\Requests\BlogsUpdateRequest;
use App\Http\Requests\DatatablesRequest;
use App\Modules\Blogs\BlogsService;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
class BlogsController extends Controller
{
public function __construct(
private readonly BlogsService $service
)
{
}
public function index(DatatablesRequest $request): JsonResponse
{
try {
return response()->json($this->service->index($request->data()));
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
public function get(int $id): JsonResponse
{
try {
return response()->json($this->service->get($id));
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
public function update(BlogsUpdateRequest $request): JsonResponse
{
try {
return response()->json($this->service->update($request));
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
public function delete(int $id): JsonResponse
{
try {
$this->service->delete($id);
return response()->json(null, Response::HTTP_NO_CONTENT);
} catch (Exception $error) {
return response()->json(
[
"exception" => get_class($error),
"errors" => $error->getMessage()
],
Response::HTTP_BAD_REQUEST
);
}
}
}
This is my blogsupdaterequest
<?php
declare(strict_types=1);
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class BlogsUpdateRequest extends FormRequest
{
public function rules(): array
{
return [
"id" => "nullable|numeric",
"is_trending" => "required|boolean",
"author" => "required|string",
"author_image_url" => "required|string",
"image_url_portrait" => "required|string",
"image_url_landscape" => "required|string",
"date" => "required|string",
"title" => "required|string",
"tags" => "required|string",
"description" => "required|string",
"content" => "required|string",
];
}
public function data(): array
{
$id = $this->input("id", null);
return [
"id" => ($id === null) ? null : (int)$id,
"is_trending" => $this->input("is_trending", 0),
"author" => $this->input("author"),
"author_image_url" => $this->input("author_image_url"),
"image_url_portrait" => $this->input("image_url_portrait"),
"image_url_landscape" => $this->input("image_url_landscape"),
"date" => $this->input("date"),
"url" => $this->generateUrl($this->input("title")),
"title" => $this->input("title"),
"tags" => array_map(function($row) {
return trim($row);
}, explode(",", $this->input("tags", []))),
"description" => $this->input("description"),
"content" => $this->input("content"),
];
}
private function generateUrl(string $title): string {
$newUrl = trim(strtolower($title));
$newUrl = str_replace(" ", " ", $newUrl);
$newUrl = str_replace(" ", "-", $newUrl);
return preg_replace("/[^A-Za-z0-9\-]/", "", $newUrl);
}
}
Blogs model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Blogs extends Model
{
protected $table = "blogs";
protected $fillable = [
"id",
"is_trending",
"author",
"author_image_url",
"image_url_portrait",
"image_url_landscape",
"title",
"date",
"description",
"content",
"created_at",
"updated_at",
];
public function tags (){
return $this->hasMany(BlogTags::class);
}
}
Blogs.blade
<div class="col-lg-8 col-12">
#foreach($blogs as $blog)
<span onclick="redirectto('{{$blog['url']}}')">
<div class="row mt-4 mb-4 blog-card border rounded">
<div class="col-lg-4 col-12 p-0 m-0">
<img src="{{$blog ['img_url_portrait']}}" alt="" class="rounded w-100 h-100">
</div>
<div class="col-lg-8 col-12 p-lg-5">
<div class="row h-100 pt-4 align-item-center">
<div class="col-12 mx-auto">
<small class="text-muted fs-8">
{{$blog ['date']}}
</small>
<br>
#foreach ($blog['tags'] as $tag)
<span class="text-primary fw-bolder fs-6 pe-1">{{$tag['$tag']}}</span>
#if($loop->iteration < count($blog['tags'])))
<span class="text-primary fw-bolder fs-6 pe-1">•</span>
#endif
#endforeach
<h2 class="fw-lighter fs-2">{{$blog['title'] }}</h2>
<p class="text-muted">{{$blog['description'] }}</p>
<p>
<img src="{{$blog['author_image_url']}}" alt="author image" class="rounded-circle" height="35" width="35">
<span class="ps-1">{{$blog['author']}}</span>
</p>
</div>
</div>
</div>
</div>
</span>
#endforeach
</div>
Images model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Images extends Model
{
protected $table = "image";
protected $fillable = [
"id",
"name",
"location",
"created_at",
"updated_at",
];
}
Form.blade
<div class="modal fade" id="BlogsModal">
<div class="modal-dialog modal-fullscreen text-dark">
<div class="modal-content">
<div class="modal-content container" style="overflow-y:scroll;">
<div class="row">
<div class="col-12 text-end">
<span type="button" class="btn-close" data-bs-dismiss="modal"></span>
</div>
<div class="col-12">
<div id="BlogsErrorsContainer" class="alert alert-danger errorContainer" style="display:none;">
<h5 class="font-weight-bolder">Error!</h5>
<ul></ul>
</div>
</div>
<div class="col-12">
<hr>
<h5 class="modal-title font-weight-bolder">New Blog</h5>
<hr>
<form id="BlogsForm">
<input type="hidden" class="form-control" id="itemId">
<div class="row">
<div class="col-12 mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="blogsIsTrending">
<label class="form-check-label">Trending</label>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Title</label>
<input type="text" class="form-control" id="blogsTitle">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Date</label>
<input type="text" class="form-control" id="blogsDate">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Name</label>
<input type="text" class="form-control" id="blogsAuthorName">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Image URL</label>
<input type="file" class="form-control" id="blogsAuthorImageUrl">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Landscape</label>
<input type="file" class="form-control" id="blogsImageUrlLandscape">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Portrait</label>
<input type="file" class="form-control" id="images[]">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Tags</label>
<input type="text" class="form-control" id="blogsTags">
<div class="form-text">Tags must be seperated by a comma. Example: <i>Laravel, Hosting</i></div>
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Description</label>
<textarea rows="2" type="text" class="form-control" id="blogsDescription"></textarea>
<div class="form-text">1-3 sentences max.</div>
</div>
<div class="col-12 mb-5">
<label class="form-label font-weight-bolder">Content</label>
<div id="blogsContent"></div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer container">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
<button id="SubmitBlogsForm" type="button" class="btn btn-sm btn-primary">Save Changes</button>
</div>
</div>
</div>
</div>
<script src="//cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
let formSubmitted = false;
let blogsEndpoint = "/api/dashboard/blogs";
let quillToolbar = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{
'header': 1
}, {
'header': 2
}], // custom button values
[{
'list': 'ordered'
}, {
'list': 'bullet'
}],
[{
'script': 'sub'
}, {
'script': 'super'
}], // superscript/subscript
[{
'indent': '-1'
}, {
'indent': '+1'
}], // outdent/indent
[{
'direction': 'rtl'
}], // text direction
[{
'size': ['small', false, 'large', 'huge']
}], // custom dropdown
[{
'header': [1, 2, 3, 4, 5, 6, false]
}],
[{
'color': []
}, {
'background': []
}], // dropdown with defaults from theme
[{
'font': []
}],
[{
'align': []
}],
['clean'] // remove formatting button
];
let quill = new Quill(
"#blogsContent", {
modules: {
toolbar: quillToolbar
},
placeholder: "Compose an epic ...",
theme: "snow"
}
);
function clearForm() {
$("#itemId").val(null);
$("#blogsTitle").val(null);
$("#blogsAuthorName").val(null),
$("#blogsAuthorImageUrl").val(null);
$("#blogsImageUrlLandscape").val(null);
$("#blogsImageUrlPortrait").val(null);
$("#blogsTags").val(null);
$("#blogsDescription").val(null);
$("#blogsDate").val(null);
$("#blogsIsTrending").prop("checked", false);
$("#blogsContent").val(null);
quill.setContents([{
insert: "\n"
}]);
clearErrors();
}
function clearErrors() {
$("#BlogsErrorsContainer ul").empty();
$("#BlogsErrorsContainer").hide();
}
function showErrors(errorsList = []) {
Object.keys(errorsList).forEach(key => {
$("#BlogsModal .errorContainer ul").append(
"<li><b>" + key + ": </b>" + errorsList[key] + "</li>"
);
$("#BlogsModal .errorContainer").show();
});
}
$(document).ready(function() {
$("#SubmitBlogsForm").click(function() {
event.preventDefault();
clearErrors();
if (formSubmitted !== true) {
formSubmitted = true;
$.ajax({
type: "POST",
url: blogsEndpoint,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
id: $("#itemId").val(),
title: $("#blogsTitle").val(),
author: $("#blogsAuthorName").val(),
author_image_url: $("#blogsAuthorImageUrl").val(),
image_url_landscape: $("#blogsImageUrlLandscape").val(),
image_url_portrait: $("#blogsImageUrlPortrait").val(),
tags: $("#blogsTags").val(),
description: $("#blogsDescription").val(),
date: $("#blogsDate").val(),
is_trending: $("#blogsIsTrending").prop("checked"),
content: quill.root.innerHTML.trim(),
}),
success: function(response) {
formSubmitted = false;
$BlogsModal.hide();
$("#dataTable").DataTable().ajax.reload();
}
}).fail(function(response) {
formSubmitted = false;
if (response.status === 422) {
showErrors(response.responseJSON["errors"]);
} else {
showErrors({
Error: "Could not process your request! Please try again later."
});
}
});
}
});
});
</script><div class="modal fade" id="BlogsModal">
<div class="modal-dialog modal-fullscreen text-dark">
<div class="modal-content">
<div class="modal-content container" style="overflow-y:scroll;">
<div class="row">
<div class="col-12 text-end">
<span type="button" class="btn-close" data-bs-dismiss="modal"></span>
</div>
<div class="col-12">
<div id="BlogsErrorsContainer" class="alert alert-danger errorContainer" style="display:none;">
<h5 class="font-weight-bolder">Error!</h5>
<ul></ul>
</div>
</div>
<div class="col-12">
<hr>
<h5 class="modal-title font-weight-bolder">New Blog</h5>
<hr>
<form id="BlogsForm">
<input type="hidden" class="form-control" id="itemId">
<div class="row">
<div class="col-12 mb-3">
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1" id="blogsIsTrending">
<label class="form-check-label">Trending</label>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Title</label>
<input type="text" class="form-control" id="blogsTitle">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Date</label>
<input type="text" class="form-control" id="blogsDate">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Name</label>
<input type="text" class="form-control" id="blogsAuthorName">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Author Image URL</label>
<input type="text" class="form-control" id="blogsAuthorImageUrl">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Landscape</label>
<input type="text" class="form-control" id="blogsImageUrlLandscape">
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<label class="form-label font-weight-bolder">Image Url Portrait</label>
<input type="text" class="form-control" id="blogsImageUrlPortrait">
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Tags</label>
<input type="text" class="form-control" id="blogsTags">
<div class="form-text">Tags must be seperated by a comma. Example: <i>Laravel, Hosting</i></div>
</div>
<div class="col-12">
<hr>
</div>
<div class="col-12">
<label class="form-label font-weight-bolder">Description</label>
<textarea rows="2" type="text" class="form-control" id="blogsDescription"></textarea>
<div class="form-text">1-3 sentences max.</div>
</div>
<div class="col-12 mb-5">
<label class="form-label font-weight-bolder">Content</label>
<div id="blogsContent"></div>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal-footer container">
<button type="button" class="btn btn-sm btn-secondary" data-bs-dismiss="modal">Close</button>
<button id="SubmitBlogsForm" type="button" class="btn btn-sm btn-primary">Save Changes</button>
</div>
</div>
</div>
</div>
<script src="//cdn.quilljs.com/1.3.6/quill.min.js"></script>
<script>
let formSubmitted = false;
let blogsEndpoint = "/api/dashboard/blogs";
let quillToolbar = [
['bold', 'italic', 'underline', 'strike'], // toggled buttons
['blockquote', 'code-block'],
[{
'header': 1
}, {
'header': 2
}], // custom button values
[{
'list': 'ordered'
}, {
'list': 'bullet'
}],
[{
'script': 'sub'
}, {
'script': 'super'
}], // superscript/subscript
[{
'indent': '-1'
}, {
'indent': '+1'
}], // outdent/indent
[{
'direction': 'rtl'
}], // text direction
[{
'size': ['small', false, 'large', 'huge']
}], // custom dropdown
[{
'header': [1, 2, 3, 4, 5, 6, false]
}],
[{
'color': []
}, {
'background': []
}], // dropdown with defaults from theme
[{
'font': []
}],
[{
'align': []
}],
['clean'] // remove formatting button
];
let quill = new Quill(
"#blogsContent", {
modules: {
toolbar: quillToolbar
},
placeholder: "Compose an epic ...",
theme: "snow"
}
);
function clearForm() {
$("#itemId").val(null);
$("#blogsTitle").val(null);
$("#blogsAuthorName").val(null),
$("#blogsAuthorImageUrl").val(null);
$("#blogsImageUrlLandscape").val(null);
$("#blogsImageUrlPortrait").val(null);
$("#blogsTags").val(null);
$("#blogsDescription").val(null);
$("#blogsDate").val(null);
$("#blogsIsTrending").prop("checked", false);
$("#blogsContent").val(null);
quill.setContents([{
insert: "\n"
}]);
clearErrors();
}
function clearErrors() {
$("#BlogsErrorsContainer ul").empty();
$("#BlogsErrorsContainer").hide();
}
function showErrors(errorsList = []) {
Object.keys(errorsList).forEach(key => {
$("#BlogsModal .errorContainer ul").append(
"<li><b>" + key + ": </b>" + errorsList[key] + "</li>"
);
$("#BlogsModal .errorContainer").show();
});
}
$(document).ready(function() {
$("#SubmitBlogsForm").click(function() {
event.preventDefault();
clearErrors();
if (formSubmitted !== true) {
formSubmitted = true;
$.ajax({
type: "POST",
url: blogsEndpoint,
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({
id: $("#itemId").val(),
title: $("#blogsTitle").val(),
author: $("#blogsAuthorName").val(),
author_image_url: $("#blogsAuthorImageUrl").val(),
image_url_landscape: $("#blogsImageUrlLandscape").val(),
image_url_portrait: $("#blogsImageUrlPortrait").val(),
tags: $("#blogsTags").val(),
description: $("#blogsDescription").val(),
date: $("#blogsDate").val(),
is_trending: $("#blogsIsTrending").prop("checked"),
content: quill.root.innerHTML.trim(),
}),
success: function(response) {
formSubmitted = false;
$BlogsModal.hide();
$("#dataTable").DataTable().ajax.reload();
}
}).fail(function(response) {
formSubmitted = false;
if (response.status === 422) {
showErrors(response.responseJSON["errors"]);
} else {
showErrors({
Error: "Could not process your request! Please try again later."
});
}
});
}
});
});
</script>

Laravel 8 Dynamic Dependent Input

it's been a while since I stuck in this problem. So I want to make a dynamic selection, when I select a nis (student_id) then the column nama (name) is filled with the student name.
Input form
Output i want
method create
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all()
]);
}
create_blade.php
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="name" required />
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
I have watched and read some questions with similar problems, and yet I still didn't get it
UPDATE
My method in my controller
public function find_nis(Request $request)
{
$data = Student::find($request->id); //Counseling::with('student', 'student.student_class')->where('student_id', $request->id)->first();
return response()->json(['view' => view('admin.counseling.create', ['data' => $data])->render()]);
}
My Ajax in create.blade.php
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change','.student_nis',function () {
var student_id = $(this).val();
var a = $(this).parent();
console.log(student_id);
var op="";
$.ajax({
type : 'GET',
url : '{!! URL::to('find_nis') !!}',
data : 'id=' + student_id,
success:function(data){
console.log(data);
a.find('.student_name').val(data.name);
},
error:function(){
}
});
});
});
</script>
My Route
Route::get('/admin/counseling/find_nis', [CounselingController::class, 'find_nis'])->name('find_nis');
this is output in my browser console when i select nis 1212
i think for getting response from DB without refresh page you should use ajax,
post student_id with ajax to Controller get username from DB and return your view like this:
in your blade:
first you must set this meta tag inside of :
<meta name="csrf-token" content="{{ csrf_token() }}">
then config and post your data with ajax like this:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
var studentId = $("input[name=student]").val();
$.ajax({
xhrFields: {withCredentials: true},
type:'POST',
url:"{{ route('getStudentInfo') }}",
data:{studentId:studentId},
success:function(data){
$('html').html(data.view);
}
});
</script>
in your Controller inside of getStudentInfo():
$student = DB::table('user')->find($studen_id);
$username = $student->username;
return response()->json(['view' => view('admin.counseling.create', compact('username'))->render()]);
Here the working solutions
*Route
Route::get('/admin/counseling/find_student', [CounselingController::class, 'find_nis'])->name('find_student');
*Controller
public function create()
{
return view('admin.counseling.create', [
'title' => 'Tambah Bimbingan dan Konseling',
'students' => Student::all(),
'problems' => Problem::all()
]);
}
public function find_nis(Request $request)
{
$student = Student::with('student_class')->findOrFail($request->id);
return response()->json($student);
}
*blade
<div class="container-fluid mt--7">
<div class="mt-8">
<div class="dashboard-content">
<div class="row">
<div class="col-12">
#if ($errors->any())
<div class="alert alert-danger">
<ul>
#foreach ($errors->all() as $error)
<li>{{ $error }}</li>
#endforeach
</ul>
</div>
#endif
<form action="/admin/counseling/store" method="post" enctype="multipart/form-data">
#csrf
<div class="card">
<div class="card-body">
<div class="row">
<div class="col-md-12">
<div class="form-group">
<label>Nomor Induk Siswa</label>
<select name="nis" required class="form-control" id="nis">
<option value="0" disabled="true" selected="true">-Pilih-</option>
#foreach($students as $student)
<option value="{{$student->id}}">{{$student->nis}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label>Nama</label>
<input type="text" class="form-control" name="student_name" id="student_name" disabled required/>
</div>
<div class="form-group">
<label>Kelas</label>
<input type="text" class="form-control" name="student_class_name" id="student_class" disabled required/>
</div>
<div class="form-group">
<label>Permasalahan</label>
<div class="row">
<div class="col">
#foreach ($problems as $problem)
<div class="form-check">
<input type="checkbox" id="" name="problem_name[]" value="{{ $problem->name }}">
<label class="fs-6 fw-light">{{ $problem->name }}</label>
</div>
#endforeach
</div>
</div>
</div>
<div class="form-group">
<label>Bobot Permasalahan</label>
<select name="priority" required class="form-control" id="nis">
<option value="null" disabled="true" selected="true">-Pilih-</option>
<option value="1">Normal</option>
<option value="3">Penting</option>
<option value="5">Sangat Penting</option>
</select>
</div>
</div>
</div>
<div class="row">
<div class="col text-right">
<button
type="submit"
class="btn btn-success px-5"
>
Simpan
</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
*ajax
<script type="text/javascript">
$(document).ready(function (){
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_name').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_name').val(data.name);
},
error:function(){
}
});
});
$(document).on('change', '#nis', function() {
var student_id = $(this).val();
var a = $('#student_class').parent();
$.ajax({
type : 'GET',
url : '{{ route('find_student') }}',
data : 'id=' + student_id,
success:function(data){
a.find('#student_class').val(data.student_class.name);
},
error:function(){
}
});
});
});
</script>

I try to update image with ajax in laravel but only details are update image is not update. How can i solve this?

Hi every one, I am using laravel 8, and i want to update data using model, now i am facing little problem. The Problem is only details are update but file or image did not updated, i give every thing in bellow,
Blade Code: THis is my datatable
<table class="table display" width="100%" id="example">
<thead>
<tr>
<th>No</th>
<th>Title</th>
<th>Image</th>
<th>Status</th>
<th>Action</th>
</tr>
</thead>
<tbody>
#php
$i=0;
#endphp
#foreach ($banner as $item )
<tr id="banner-{{ $item->id }}">
<td>{{ ++$i }}</td>
<td>{{ $item->title }}</td>
<td><img src="{{ asset('/assets/image/banner/'.$item->image) }}" alt="" style="width: 100px; height:100px"></td>
<td><input type="checkbox" name="status" class="status" id="status" data-toggle="toggle" data-on="Active" data-off="Deactive" data-onstyle="success" data-offstyle="danger" data-id="{{ $item->id }}" {{ $item->status == 'Active' ? 'checked' : '' }}></td>
<td>
<a class="btn btn-outline-warning btn-sm" href="javascript:void(0);" onclick="editbanner({{ $item->id }})"><i class="fas fa-pencil-alt"></i></a>
<i class="mdi mdi-trash-can"></i>
</td>
</tr>
#endforeach
</tbody>
</table>
Update Model here is data update model, that i create for update data.
<div class="modal fade" id="BannerEditModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalCenterTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="text-center">
<h3 class="modal-title" id="exampleModalLabel">Insert Position & Salary</h3>
</div>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul id="BannerForm_errorlist"></ul>
<form class="forms-sample" id="bannereditform" method="post">
#csrf
<input type="hidden" name="id" id="id">
<div class="form-group">
<label>Title<small class="text-danger">*</small></label>
<input type="text" id="title1" name="title1" class="form-control" />
</div>
<div class="form-group">
<label>Banner Image<small class="text-danger">*</small></label>
<input type="file" id="image1" name="image1" class="form-control" />
</div>
<div class="text-center pb-2">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success submit" name="submit" id="submit" value="Update" />
</div>
</form>
</div>
</div>
</div>
Ajax Part This is Ajax code for data fetching and data uploading
function editbanner(id) {
$.get("/banner/edit/" + id, function(banner) {
$('#id').val(banner.id);
$('#title1').val(banner.title);
$('#BannerEditModal').modal("toggle");
});
}
$('#bannereditform').submit(function(e) {
e.preventDefault();
let id = $('#id').val();
var title1 = $('#title1').val();
var image1 = $('#image1').val();
let _token = $('input[name=_token]').val();
console.log(image1);
$.ajax({
type: "PUT"
, url: "/banner/update"
, data: {
id: id
, title1: title1
, image1: image1
, _token: _token
, }
, dataType: "json"
, success: function(response) {
// console.log(response);
$('#banner' + response.id + 'td:nth-child(1)').text(response.title1);
$('#banner' + response.id + 'td:nth-child(2)').val(response.image1);
$('#BannerEditModal').modal("toggle");
// location.reload();
$('#bannereditform')[0].reset();
}
});
});
Controller
public function update(Request $request)
{
$banner = Banner::find($request->id);
$banner->title = $request->input('title1');
if($request->hasFile('image1')){
$destination = public_path().'/assets/image/banner/'.$banner->image;
if(File::exists($destination)){
File::delete($destination);
}
$image = $request->file('image1');
$image_name = time().'.'.$image->getClientOriginalExtension();
$image->move(public_path().'/assets/image/banner/',$image_name);
$banner->image = $image_name;
}
$banner->save();
return response()->json($banner);
}
Route Here is my data fatching and data updating route
Route::get('/banner/edit/{id}', "App\Http\Controllers\BannerController#edit")->name('banner.edit');
Route::put('/banner/update', "App\Http\Controllers\BannerController#update")->name('banner.update');
you need to change the way you getting value from #image from
var image1 = $('#image1').val();
to
var image1 = $('#image1').prop('files')[0]
You are missing enctype in your modal form:
The enctype attribute specifies how the form-data should be encoded when submitting it to the server.
Note: The enctype attribute can be used only if method="post".
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<div class="text-center">
<h3 class="modal-title" id="exampleModalLabel">Insert Position & Salary</h3>
</div>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<ul id="BannerForm_errorlist"></ul>
<form class="forms-sample" id="bannereditform" method="post" enctype="multipart/form-data">
#csrf
<input type="hidden" name="id" id="id">
<div class="form-group">
<label>Title<small class="text-danger">*</small></label>
<input type="text" id="title1" name="title1" class="form-control" />
</div>
<div class="form-group">
<label>Banner Image<small class="text-danger">*</small></label>
<input type="file" id="image1" name="image1" class="form-control" />
</div>
<div class="text-center pb-2">
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
<input type="submit" class="btn btn-success submit" name="submit" id="submit" value="Update" />
</div>
</form>
</div>
</div>
Ajax : to send form files and data to Back-end we are using Form Data objects:
$('#bannereditform').submit(function(e) {
e.preventDefault();
let formData = new FormData($('#bannereditform')[0]);
$.ajax({
type: "PUT"
, url: "/banner/update"
, data:formData,
, dataType: "json",
processData: false
, success: function(response) {
// console.log(response);
$('#banner' + response.id + 'td:nth-child(1)').text(response.title1);
$('#banner' + response.id + 'td:nth-child(2)').val(response.image1);
$('#BannerEditModal').modal("toggle");
// location.reload();
$('#bannereditform')[0].reset();
}
});})

datatables ajax routes not working on local network

My problem occur in a specific case,
I'm using laravel 7, trying to make small contacts list datatable using ajax CRUD operations .
On localhost every thing is OK but when I deploy it to local network I get (404 not found ajax response)
may controller code:
public function index(Request $request)
{
$cities = State::where("country_id",223 )->get();//223 turkey
$countries = [];
$countries = Country::all(); //select('name')->get()
$datasources = [];
$datasources = DB::table('contacts')->select('data_source')->distinct()->get()->toArray();
$contact_types = [];
$contact_types = DB::table('contacts')->select('contact_type')->distinct()->get()->toArray();
$data = DB::table("contacts")
->leftjoin("countries","contacts.country","=","countries.id")
->leftjoin("states","contacts.city","=","states.id")
->select("contacts.*", "countries.name as countryname", "states.name as statename")
->latest()->get();
if ($request->ajax()) {
return Datatables::of($data)
->addIndexColumn()
->addColumn('action', function($row){
$btn = 'edit';
$btn = $btn.' delete';
return $btn;
})
->rawColumns(['action'])
->make(true);
}
return view('contacts.contactAjax')->with([ 'contacts'=>$data,
'countries'=> $countries,
'cities'=> $cities,
'datasources'=> $datasources,
'contact_types'=> $contact_types]); //,compact('contacts'));
}
and here may whole view code:
#extends('contacts.layout')
#section('content')
<div class="container">
<h1>Arabist CRM </h1>
<a class="btn btn-success" href="javascript:void(0)" id="createNewContact"> Add contact</a>
<button id="btn-export">EXCEL</button>
{{--onclick="exportTableToExcel('tbl_contacts','conts.xlsx')" <a class="btn btn-success" href="javascript:exportTableToExcel('tbl_contacts','contacts.xlsx')" id="xlsx-export"> excel</a> --}}
<table class="table table-bordered data-table" id="tbl_contacts">
<thead>
<tr>
<th style="padding:10pt 20pt 2pt 2pt; background-image:none;" width="20pt">No</th>
<th style="min-width:75pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="10%">name</th>
<th style="min-width:50pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="10%">company</th>
{{-- <th width="10%">birth</th>
<th>الجنس</th> --}}
<th style="min-width:75pt; padding:10pt 20pt 2pt 2pt; background-image:none;" >email</th>
<th style="min-width:50pt; padding:10pt 20pt 2pt 2pt; background-image:none;">phone</th>
<th style="min-width:120pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="15%">notes</th>
<th style="min-width:40pt; padding:10pt 20pt 2pt 2pt; background-image:none;">contact type</th>
<th style="min-width:40pt; padding:10pt 20pt 2pt 2pt; background-image:none;">city</th>
<th style="min-width:65pt; padding:10pt 20pt 2pt 2pt; background-image:none;">address</th>
<th style="min-width:80pt; padding:10pt 20pt 2pt 2pt; background-image:none;" width="8%" style="min-width:100px">control</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
<div class="modal fade" id="ajaxModel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title" id="modelHeading"></h4>
</div>
<div class="modal-body">
<form id="contactForm" name="contactForm" class="form-horizontal">
<input type="hidden" name="id" id="id">
<div class="form-group">
<label for="name" class="col-sm-2 control-label">name</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="name" name="name" placeholder="Enter Name" value="" maxlength="50" required="">
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">company</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="company_name" name="company_name" placeholder="Enter Name" value="" maxlength="50" >
</div>
</div>
<div class="form-group">
<label for="email" class="col-sm-2 control-label">email</label>
<div class="col-sm-12">
<input type="email" class="form-control" id="email" name="email" placeholder="Enter Name" value="" >
</div>
</div>
<div class="form-group">
<label for="phone" class="col-sm-2 control-label">phone</label>
<div class="col-sm-12">
<input type="tel" class="form-control" id="phone" name="phone" placeholder="Enter Name" value="" maxlength="50" required="required">
</div>
</div>
<div class="form-group">
<label for="contact_type" class="col-sm-2 control-label">type</label>
<div class="col-sm-12">
<input class="form-control" type="text" list="contact_types" name="contact_type" id="contact_type" placeholder="type" />
<datalist name = "contact_types" id = "contact_types" >
#foreach ($contact_types as $ctp)
<option >{{ $ctp->contact_type }}</option>
#endforeach
</datalist>
</div>
</div>
<div class="form-group" style="display:none;">
<label for="country" class="col-sm-2 control-label" >country</label>
<div class="col-sm-12">
<select class="form-control input-sm" name="country" id="country">
<option value="">--select--</option>
#foreach ($countries as $cnt)
#if($cnt->id == 223 )
<option value="{{ $cnt->id }}" selected>{{$cnt->name}}</option>
#else
<option value="{{ $cnt->id }}">{{$cnt->name}}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group" style="display:none;">
<label for="city" class="col-sm-2 control-label">city</label>
<div class="col-sm-12">
<select class="form-control input-sm" name="city" id="city">
<option value="">--select--</option>
#foreach ($cities as $cnt)
#if($cnt->id == 3703 )
<option value="{{ $cnt->id }}" selected>{{$cnt->name}}</option>
#else
<option value="{{ $cnt->id }}">{{$cnt->name}}</option>
#endif
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label for="address" class="col-sm-2 control-label">address</label>
<div class="col-sm-12">
<input type="text" class="form-control" id="address" name="address" placeholder="Enter address" maxlength="50" >
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">notes</label>
<div class="col-sm-12">
<textarea id="notes" name="notes" required="" placeholder="Enter Details" class="form-control"></textarea>
</div>
</div>
<div class="col-sm-offset-2 col-sm-10">
more details
<button type="submit" class="btn btn-primary" id="saveBtn" value="create">save
</button>
</div>
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
var table = $('#tbl_contacts').DataTable({
processing: true,
serverSide: true,
ajax: "{{ route('ajaxcontacts.index') }}",// "{{ route('ajaxcontacts.index') }}",{{ url('ajaxcontacts.index')}}
columns: [
{data: 'DT_RowIndex', name: 'DT_RowIndex'},
{data: 'name', name: 'name'},
{data: 'company_name', name: 'company_name'},
{data: 'email', name: 'email'},
{data: 'phone', name: 'phone'},
{data: 'notes', name: 'notes'},
{data: 'contact_type', name: 'contact_type'},
{data: 'statename', name: 'city'},
{data: 'address', name: 'address'},
{data: 'action', name: 'action', orderable: false, searchable: false},
]
});
$('#btn-export').click(function () {
exportTableToExcel("tbl_contacts","fuc.xlsx");
});
$('#createNewContact').click(function () {
$('#saveBtn').val("create-contact");
$('#id').val('');
$('#contactForm').trigger("reset");
$('#modelHeading').html("Create New Contact");
$('#ajaxModel').modal('show');
});
$('body').on('click', '#moreDetails', function () {
var id = $('#id').val();
alert("id: "+ id);
window.location.href = "contacts" +'/' + id +'/edit';//"{{ route('contacts.index') }}"
//$.get("{{ route('contacts.index') }}" +'/' + id +'/edit')
});
$('body').on('click', '.editContact', function () {
var id = $(this).data('id');
//alert("id: "+ id);
$.get( "{{ route('ajaxcontacts.index') }}" + "/" + id +"/edit", function (data) {
//alert("data.name: " + data.name)
$('#modelHeading').html("Edit Contact");
$('#saveBtn').val("edit-user");
$('#ajaxModel').modal('show');
$('#id').val(data.id);
$('#name').val(data.name);
$('#company_name').val(data.company_name);
$('#email').val(data.email);
$('#phone').val(data.phone);
$('#notes').val(data.notes);
$('#contact_type').val(data.contact_type);
$('#data_source').val(data.data_source);
$('#country').val(data.country);
$('#city').val(data.city);
$('#address').val(data.address);
})
});
$('#saveBtn').click(function (e) {
e.preventDefault();
$(this).html('Sending..');
$.ajax({
data: $('#contactForm').serialize(),
url: "{{ route('ajaxcontacts.store') }}",
type: "POST",
dataType: 'json',
success: function (data) {
$('#contactForm').trigger("reset");
$('#ajaxModel').modal('hide');
table.draw();
},
error: function (data) {
console.log('Error:', data);
$('#saveBtn').html('save changes');
}
});
});
$('body').on('click', '.deleteContact', function () {
var id = $(this).data("id");
confirm("Are You sure want to delete !");
$.ajax({
type: "DELETE",
url: "{{ route('ajaxcontacts.store') }}"+'/'+id,
success: function (data) {
table.draw();
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
</script>
</body>
#endsection
and web.php routes
Route::resource('ajaxcontacts','ContactAjaxController')->Middleware('isAdmin');
Route::get('ajaxcontacts/index', 'ContactAjaxController#index');
The issue is that you are calling a route from your ajax code, but you have not set up a named route within your web.php route file.
When you use the route() method, Laravel looks for a named route. You call this method several times in your blade file here:
"{{ route('ajaxcontacts.index') }}"
To Fix just name the route in your web.php file:
Route::get('ajaxcontacts/index', 'ContactAjaxController#index')->name('ajaxcontacts.index');

how to make ajax call inside a edit form view in laravel

i have created a form for editing the record from db there is different time slots and i want to make delete function for them so i made a ajax call but am confused in URL www.hostname.com/dental/public/admin/manageschedule/1/api/ajax 404 (Not Found)
how to call ajax inside a laravel edit form
here is what i have done:
#extends('admin.layouts.app_inner')
#section('htmlheader_title')
Home
#endsection
#section('content')
#if (count($errors))
#foreach($errors->all() as $error)
<div class="alert alert-danger"><i class="fa fa-fw fa-close"></i> {{ $error }}</div>
#endforeach
#endif
#if ($message = Session::get('success'))
<div class="alert alert-success alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>
<h4><i class="icon fa fa-check"></i>Success</h4>
{{ $message }}
</div>
#endif
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title text-green"><b>Add Schedule</b></h3>
</div>
<!-- /.box-header -->
<!-- form start -->
<div class="box-body">
{!! Form::model($doctors, ['method' => 'PATCH','route' => ['manageschedule.update', $doctors->doctor_id],'class' => 'form-horizontal','files'=>true]) !!}
<div class="form-group">
<label class="col-md-3 control-label"> Select Doctor :</label>
<div class="col-md-5">
<select class="form-control" required name="doctor_name">
<?php $results = DB::select(DB::raw("SELECT day FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' Order BY id DESC ")); ?>
<option value="{{$doctors->doctor_name}}" SELECTED="YES">{{$doctors->doctor_name}}</option>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label" required> Day :</label>
<div class="col-md-5">
<div class="md-checkbox-inline">
<?php $day = array('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'); ?>
#foreach($day as $days)
<input name="day[]" value="<?php echo $days; ?>" type="checkbox" class="md-checkbox" <?php
foreach ($results as $row) {
if ($row->day == $days) {
echo 'checked="checked"';
} else {
}
}
?> >
<label for="checkbox7"> <?php echo $days; ?> </label>
#endforeach
</div>
</div>
</div>
<?php foreach ($results as $row) { $d=$row->day;}
$result= DB::select(DB::raw("SELECT * FROM schedule_times where doctor_id='" . $doctors->doctor_id . "' And day='".$d."' "));
?>
<div class="form-group">
<label class="col-md-3 control-label" required>Time slots</label>
<div class="col-md-6">
<table class="table table-bordered" id="employee_table" width="50%" >
<th>Start Time</th>
<th>End Time</th>
<th>Manage</th>
<?php foreach ($result as $key=>$vari) {
$id = $vari->id;
?>
<tr id="row1">
<td><div class="input-group ">
<input type="text" class="form-control" id="time" placeholder="Start Time" name="s_time[]" value="<?php echo $vari->start_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<td><div class="input-group ">
<input type="text" class="form-control" id="time1" placeholder="Start Time" name="e_time[]" value="<?php echo $vari->end_time; ?>" >
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div></td>
<?php if ($key == 0) { ?>
<td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' disabled></td>
<?php } else { ?>
<td><span class='delete' id='del_<?php echo $id; ?>'><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' id='del_<?php echo $id; ?>' ></td>
</tr>
<?php }
}
?>
</table>
<a type="button" onclick="add_rows();" class="fa fa-plus-circle btn btn-primary"> Add More Time Slots</a>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label"> Per Patient Time :</label>
<div class="col-md-5">
<div class=" input-daterange">
<input type="text" name="p_time" class="form-control" placeholder="Set per patient time" id="time1" value="<?php
echo $result[0]->p_time; ?>">
<span class="help-block"> You can set only minute </span>
</div>
</div>
</div>
<div class="form-group">
<label class="col-md-3 control-label">Visibility :</label>
<div class="col-md-5">
<input type="radio" id="checkbox2_5" value="Yes" name="visible" class="md-radiobtn" <?php
foreach($result as $check)
{
if($check->visibility=='Yes'){ echo 'checked="checked"';}else{}
} ?> >
<label for="checkbox2_5"> Yes </label>
<input type="radio" id="checkbox2_10" value="No" name="visible" class="md-radiobtn" <?php foreach($result as $check)
{
if($check->visibility=='No'){ echo 'checked="checked"';}else{}
} ?>>
<label for="checkbox2_10"> No </label>
</div>
</div>
<br><br>
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right"id="submit">Update Schedule </button>
</div>
{!! Form::close() !!}
</div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time').timepicker();
})
});
</script>
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$('#time1').timepicker();
})
});
</script>
<script type="text/javascript">
function add_rows()
{
$rowno = $("#employee_table tr").length;
$rowno = $rowno + 1;
$("#employee_table tr:last").after("<tr id='row" + $rowno + "'><td><div class='input-group '><input type='text' class='form-control' placeholder='Start Time' name='s_time[]' onclick=showtime('row" + $rowno + "')><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><div class='input-group '><input type='text' class='form-control' id='time1' placeholder='End Time' name='e_time[]'><span class='input-group-addon'><span class='glyphicon glyphicon-time'></span></span></div> </td><td><input type='button' class='fa fa-plus fa-4 btn btn-primary' value='DELETE' onclick=delete_row('row" + $rowno + "')></td></tr>");
}
function delete_row(rowno)
{
$('#' + rowno).remove();
}
</script>
<script type="text/javascript">
//Variant Deleting script///
$(document).ready(function () {
// Delete
$('.delete').click(function () {
var el = this;
var id = this.id;
var splitid = id.split("_");
// Delete id
var deleteid = splitid[1];
alert('Are you sure you want to delete?');
$.ajax({
url: 'api/ajax',
type: 'delete',
data: {id: deleteid},
success: function (response) {
// Removing row from HTML Table
$(el).closest('tr').css('background', 'tomato');
$(el).closest('tr').fadeOut(800, function () {
$(this).remove();
});
}
});
});
});
</script>
<meta name="_token" content="{!! csrf_token() !!}" />
#endsection
here is my controller of api
Route::post('ajax','Controller#ajax')->name('ajax');
here is my web route:
Route::get('/', function () {
return view('auth.login');
});
Route::post('/', function () {
return view('auth.login')->with('successMsg','Please Select A role .');
});
Route::prefix('admin')->group(function() {
Route::get('/login', 'Auth\AdminLoginController#showLoginForm')->name('admin.login');
Route::post('/login', 'Auth\AdminLoginController#login')->name('admin.login.submit');
Route::get('/', 'AdminController#index')->name('admin.home');
Route::resource('managedoctor', 'AddDocController');
Route::resource('managefront', 'AddFrontController');
Route::resource('managepatient', 'AddPatientController');
Route::resource('manageschedule', 'AddScheduleController');
Route::get('/logout', 'Auth\AdminLoginController#logout')->name('admin.logout');
});
Route::prefix('doctor')->group(function() {
Route::get('/login', 'Auth\DoctorLoginController#showLoginForm')->name('doctor.login');
Route::post('/login', 'Auth\DoctorLoginController#login')->name('doctor.login.submit');
Route::get('/', 'DoctorController#index')->name('doctor.home');
Route::get('/logout', 'Auth\DoctorLoginController#logout')->name('doctor.logout');
});
Route::prefix('frontdesk')->group(function() {
Route::get('/login', 'Auth\FrontdeskLoginController#showLoginForm')->name('frontdesk.login');
Route::post('/login', 'Auth\FrontdeskLoginController#login')->name('frontdesk.login.submit');
Route::get('/', 'FrontdeskController#index')->name('frontdesk.home');
Route::get('/logout', 'Auth\FrontdeskLoginController#logout')->name('frontdesk.logout');
});
my issue is resolved now the mistake i have done is i was not using the same route group in which am calling the controller with AUTH method

Resources