Laravel using ajax get records from controller - javascript

Am trying to get data from controller and append to "tbody" using Ajax, yet am getting blank page.
Controller:
public function getRecordsMD(){
$filedata = File::where('uploaded_by', '=', auth()->user()->username)->get();
return response()->json([
'filedata'=>$filedata,
]);
}
Route:
Route::get('/manage_document',[utemfilesharing::class, 'getRecordsMD']);
Ajax/Jquery:
$(document).ready(function () {
getRecordsMD();
//Get all records
function getRecordsMD() {
$.ajax({
type:'GET',
url: '/manage_document',
dataType: "json",
success: function(data){
console.log(data.filedata);
$.each(data.filedata, function (key, item) {
$('tbody').append('<tr>\
<td>'+item.id+'</td>\
<td>'+item.name+'</td>\
<td>'+item.faculity_name+'</td>\
<td>'+item.document_type+'</td>\
<td>'+item.subject_name+'</td>\
<td>'+item.description+'</td>\
<td>\
<button type="button" id="editFiles" class="btn btn-success btn-sm" data-bs-toggle="modal" data-bs-target="#edit-model" data-id="'+item.id+'"><i class="fas fa-edit"></i></button>\
<button type="button" id="deleteFiles" class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#delete-model" data-id="'+item.id+'"><i class="fas fa-trash"></i></button>\
</td>\
</tr>');
});
},
error: function (data) {
console.log('Error:', data);
}
});
}
});
View:
<!-- Manage Document -->
<div class="col-xl-12 col-md-6 mb-4">
<div class="card shadow mb-4">
<!-- Card Header - Dropdown -->
<div
class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
<h6 class="m-0 font-weight-bold text-primary">Manage Document</h6>
</div>
<!-- Card Body -->
<div class="card-body">
<div class="alert alert-success" role="alert" id="successMsg" style="display: none" >
File Updated successfully!
</div>
<div class="alert alert-danger" role="alert" id="successDMsg" style="display: none" >
File Delete successfully!
</div>
<table id="manageDocument" class="table table-striped table-bordered" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>File Name</th>
<th>Faculity Name</th>
<th>Document Type</th>
<th>Subject Name</th>
<th>Description</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
<script src="{{asset('vendor\bootstrap\js\bootstrap5-1-3.bundle.min.js')}}"></script>
<script src="{{asset('vendor\jquery\jquery.min.js')}}"></script>
<script src="{{asset('js\Models.js')}}"></script>
It seems like am missing something I don't know what its. whenever I navigate to /manage_document I get a blank page where it suppose display the table. will be glad if you help.

Related

how to change the bind grid view in separately

I created one grid view to get the database table details,
here, when I click the Next Sync button it will pop up this box and I can choose the date and time,
but the problem is when I clicked any Next Sync button only change the first DateTime only,
this is the code of the table grid view
<table class="table table-striped border-bottom">
<thead>
<tr>
<th>Select to Sync.</th>
<th class="sorting">Source</th>
<th>Last Sync. Date</th>
<th>Download</th>
<th>Status</th>
<th>Next Sync Schedule</th>
<th>Schedule</th>
</tr>
</thead>
<tbody data-bind="foreach: PayrollIntegrationVM.GridDataList">
<tr>
<td><input type="checkbox" data-bind="checked:SHTYP_IS_MANUAL_SYNC"
class="i-checks" name="foo"></td>
<td data-bind="text:SHTYP_NAME"></td>
<td data-bind="text: moment(SHTYP_LAST_DATE).format('L LTS')"></td>
<td>
<div data-bind="ifnot: SHTYP_SYNC_STATUS">
<a href="#" data-bind="click: PayrollIntegrationVM.ErrorLog">
<span class="mr-2">
<img src="~/Content/img/icon-excel.png"
alt="Download">
</span> Download Error Log
</a>
</div>
</td>
<td data-bind="text: SHTYP_SYNC_STATUS? 'Success' : 'Failed'"><a href="#">
<i class="fa fa-close text-danger"></i></a></td>
<td data-bind="text: moment(SHTYP_NEXT_DATE).format('L LTS')" id="SHTYP_NEXT_DATE_GET"
name="Sync_Next_Date"></td>
<td><a href="#" id="Next-Sync-Value" data-toggle="modal" data-target="#sync"
name="Next_Sync_button">Next Sync.</a></td>
</tr>
</tbody>
this is the date time picker code
<div class="modal" id="sync" tabindex="-1" role="dialog">
<div class="modal-dialog">
<div class="modal-body">
<div class="col ml-5 d-flex flex-column justify-content-end">
<input type="date" class="form-control" id="NextSyncDate">
<input type="time" class="form-control mt-2" id="NextSyncTime">
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-white" data-dismiss="modal">
Cancel
</button>
<button type="button" class="btn btn-primary" data-dismiss="modal" onclick="DoneButtonFunction()">Done</button>
</div>
</div>
</div>
</div>
this is the script part
<script language="JavaScript">
function DoneButtonFunction() {
var nextSyncDate = $('#NextSyncDate').val();
var nextSyncTime = $('#NextSyncTime').val();
var DateTime = nextSyncDate +" "+ nextSyncTime;
document.getElementById('SHTYP_NEXT_DATE_GET').innerHTML = DateTime;
}
}
</script>
it looks like in your js function, you find the element with the ID 'SHTYP_NEXT_DATE_GET', and js looks for the first one, try to save the row in the table, or find another way to Identify which 'SHTYP_NEXT_DATE_GET' element you want to edit

On click function firing more times every time button is clicked

I had an initial issue where I could not get a button within a modal to work.
I got my solution; however, it ended up breaking the main screen table's button events. I figured separating the scripts into different files and including the file to use specific js files on certain cshmtl pages would solve my problem; however, it's causing me more grief. I had all of these scripts in one file, if there is a solution where all my buttons work inside and outside the modal, I will be happy to take that route.
I think I have it just about figured out -- but now when I click the "add user" button once it's fine. If i click it twice, two modals pop up. If I click it 3 times it freaks out. I am unsure what to do about the problem. I am not the most proficient in js/jQuery, very new and learning.
Main Page:
<link rel="stylesheet" href="~/css/Maintenance.css" />
<link rel="stylesheet" href="~/css/Index.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="~/js/Maintenance.js"></script>
<div class="tableContainer">
<div class="maintHeader">
<div class="headerText">
All Users
#*This button is the one causing issues -----------------------------------*#
<button class="sqButton btnGreen float-right" title="Register"
data-toggle="ajax-modal"
data-target="#register"
data-url="#Url.Action("Register", "Home")">
<i class="glyphicon glyphicon-plus"></i>
</button>
#*-------------------------------------------------------------------------*#
</div>
</div>
#if (Model.Any())
{
//--Table Header Declaration--
<div class="wrapper">
<div class="scrollTable">
<table class="table table-hover table-md ">
<thead>
<tr>
<th class="text-left tableHead d-none">Id</th>
<th class="text-left tableHead">User Name</th>
<th class="text-left tableHead">Email</th>
<th class="text-left tableHead">Phone Number</th>
<th class="text-left tableHead">City</th>
<th class="text-left tableHead text-right">Remove</th>
</tr>
</thead>
#*--Table Body For Each to pull DB records--*#
<tbody>
#foreach (var user in Model)
{
#Html.Partial("~/Views/Administration/Users/UserTable.cshtml", user)
}
</tbody>
</table>
</div>
</div>
}
<div id="modal-placeholder"></div>
</div>
Modal HTML:
<link rel="stylesheet" href="~/css/Modals.css" />
<script src="~/lib/jquery/dist/jquery.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.js"></script>
<script type="text/javascript" src="~/js/MaintModals.js"></script>
<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="loginLabel" aria-hidden="true" data-keyboard="false" data-backdrop="static">
<div class="modal-dialog modalPosition" role="document">
<div class="modal-content">
<div class="modal-header headerFormat">
<span class="modal-title TitleFont">Login</span>
<button type="button" class="close closePadding" data-dismiss="modal" aria-label="Close">
<span class="xColor" aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="post" class="mt-3" asp-controller="Account" asp-action="Login">
<div class="form-group row text-center">
<label class="col-sm-3 text-right col-form-label labelFont" asp-for="Email"></label>
<div class="col-sm-7">
<input asp-for="Email" class="formField" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label class="col-sm-3 text-right col-form-label labelFont" asp-for="Password"></label>
<div class="col-sm-7">
<input asp-for="Password" class="formField" />
<span asp-validation-for="Password" class="text-danger"></span>
</div>
</div>
<div class="form-group row text-center">
<label asp-for="RememberMe" class="col-sm-4 text-right col-form-label labelFont" />
<div class="col-sm-12">
<input asp-for="RememberMe" />
#Html.DisplayNameFor(m => m.RememberMe)
</div>
</div>
<div asp-validation-summary="All" class="text-danger"></div>
<button type="submit" class="btn btn-primary padFloat green">Login</button>
<button type="button" class="btn btn-secondary padFloat blue" data-dismiss="modal">Close</button>
</form>
</div>
</div>
</div>
</div>
Maintenance.js:
$(function () {
var placeholderElement = $('#modal-placeholder');
$('[data-toggle="ajax-modal"]').click(function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});
});
MaintModal.js:
$(function () {
$(document).on('click', '[data-dismiss="modal"]', function () {
$(".modal-backdrop").remove();
});
});
$(function () {
var placeholderElement = $('#modal-placeholder');
$(document).on('click', '[data-toggle="ajax-modal"]', function (event) {
var url = $(this).data('url');
$.get(url).done(function (data) {
placeholderElement.html(data);
placeholderElement.find('.modal').modal('show');
});
});
});
site.js:
$('.sqButton').click( function (event) {
event.stopPropagation();
});
I just want my parent table's buttons to work and the buttons within the modal to work. I attempted to unbind ($('[data-toggle="ajax-modal"]').unbind("click");) the event before each event but that fixed nothing.
I am sure there's a simple way to do it. I have just been dancing around it and making it more complicated than it should be.

DataTables won't work in a modal

I have a table, where on row click a modal window is opened. Thanks to this:
th:onclick="'javascript:openPoolModal(\''+ ${networkHashrate.id} + '\');'"
openPoolModal.js looks like:
function openPoolModal(id){
$.ajax({
url: "/" + id,
success: function(data){
$("#PoolModalHolder").html(data);
$("#personalModal").modal();
$("#personalModal").modal('show');
}
});
}
PoolModalHolder is just an empty div on my main.html file, where the first table is rendered. personalModal is a fragment of code that opens on a modal dialog.
A modal dialog is then filled with personalModal:
<div class="modal fade" id="personalModal" role="dialog" th:fragment="modalContents">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title" th:text="'Network Id: ' + ${poolHashrates[0].networkHashrate.id}">Network Id</h4>
</div>
<div class="modal-body">
<div class="table-responsive">
<table width="100%" class="table table-hover " id="poolTable">
<thead class="thead-inverse">
<tr>
<th class="col-md-2 text-center">Pool name</th>
<th class="col-md-2 text-center">Date from</th>
<th class="col-md-2 text-center">Hashrate</th>
</tr>
</thead>
<tbody>
<tr th:each="poolHashrate : ${poolHashrates}">
<td class="text-center" th:text="${poolHashrate.poolDef.name}"> Sample data</td>
<td class="text-center" th:text="${poolHashrate.poolDef.date_from}">Maven Street 10, Glasgow</td>
<td class="text-center" th:text="${poolHashrate.hashrate}">999-999-999</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
I can't get the DataTables to work on the table inside personalModal window.
The standard DataTables initialization doesn't work and that is:
$(document).ready( function () {
$('#poolTable').DataTable();
} );
I have also tried this, but with same result:
$( "#personalModal" ).focus(function() {
$('#poolTable').DataTable();
});
I have header links added and those are: jQuery, Bootstrap, DataTables.js.
I have also tried with table-responsive example, but again, doesn't work. Data is generated correctly through Spring controller method. I just need to apply sorting & pagination to the table.

How do I correctly use typeahead.js to autocomplete and retrieve data?

I have an old autocomplete.js code and with modification I tried to migrate it to typehead.js. The problem is I quite didn't find any results similar to angular and ajax.
Here's my script.
$('#empid').typeahead({
minLength: 1,
source: function (request, response) {
$.ajax({
url: "http://localhost:2222/api/search/PostSearch",
type: "POST",
data: "{'eid':'" + document.getElementById('empid').value + "'}",
dataType: 'json',
success: function (data) {
response(jQuery.parseJSON(data));
}
});
}
});
So How do I correctly do this. Help would be much appreciated.
Hi added the html script. Still couldn't let it to work. Can you help?
<script src="../../js/form-search.js"></script>
<!-- .page-content -->
<div ng-controller="SearchController" class="page-content clearfix">
<!-- .page-content-wrapper -->
<div class="page-content-wrapper">
<div class="page-content-inner">
<!-- Start .page-content-inner -->
<div id="page-header" class="clearfix">
<div class="page-header">
<h2>Search Employee</h2>
<span class="txt">Search and manage employees</span>
</div>
<div class="header-stats">
<div class="spark clearfix">
<div class="spark-info"><span class="number">2345</span>Visitors</div>
<div id="spark-visitors" class="sparkline"></div>
</div>
<div class="spark clearfix">
<div class="spark-info"><span class="number">17345</span>Views</div>
<div id="spark-templateviews" class="sparkline"></div>
</div>
<div class="spark clearfix">
<div class="spark-info"><span class="number">3700$</span>Sales</div>
<div id="spark-sales" class="sparkline"></div>
</div>
</div>
</div>
<!-- Start .row -->
<div class="row">
<div class="col-lg-12">
<!-- col-lg-12 start here -->
<div class="panel panel-default plain toggle panelMove panelClose panelRefresh">
<!-- Start .panel -->
<div class="panel-heading">
<h4 class="panel-title">Basic Data tables</h4>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label" for="">Employee id</label>
<div class="col-lg-10 col-md-9">
<input id="empid" ng-model="searchedDetail.id" type="text" class="form-control" name="empid" />
</div>
</div>
<!-- End .form-group -->
<div class="form-group">
<label class="col-lg-2 col-md-3 control-label" for="">Employee name</label>
<div class="col-lg-10 col-md-9">
<input id="ename" ng-model="searchedDetail.ename" type="text" class="form-control" name="ename">
</div>
</div>
<!-- End .form-group -->
<div class="row">
<div class="col-lg-9 col-sm-9 col-xs-12 col-sm-offset-3">
<button id="btnSearch" type="submit" ng-click="searchb()" class="btn btn-default pad">Search</button>
</div>
</div>
<table id="basic-datatables" class="table table-striped table-bordered" cellspacing="0" width="100">
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Date Of Birth</th>
<th>Gender</th>
<th>email</th>
<th>mobile no</th>
<th>designation</th>
<th>date of join</th>
<th>nic</th>
<th>department name</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in employes" style="text-align:center">
<td>{{emp.fname}}</td>
<td>{{emp.lname}}</td>
<td>{{emp.DOB}}</td>
<td>{{emp.gender}}</td>
<td>{{emp.email}}</td>
<td>{{emp.mobile_no}}</td>
<td>{{emp.designation}}</td>
<td>{{emp.date_of_join}}</td>
<td>{{emp.nic}}</td>
<td>{{emp.department_name}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<!-- End .panel -->
</div>
<!-- col-lg-12 end here -->
</div>
<!-- End .row -->
</div>
<!-- End .page-content-inner -->
</div>
<!-- / page-content-wrapper -->
</div>
<!-- / page-content -->
Here is a complete working solution
function BindEmployeeTypeAhead() {
$.ajax({
type: "POST",
url: "http://localhost:2222/api/search/PostSearch",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: SuccessBindEmployeeTypeAhead,
error: FailureBindEmployeeTypeAhead
});
}
function SuccessBindEmployeeTypeAhead(response) {
try {
if (response == "")
return;
var dataSource = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('EmployeeID', 'EmployeeName'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
local: JSON.parse(response)
});
dataSource.initialize();
$("#empid").typeahead({
hint: true,
highlight: true,
minLength: 1
},
{
display: function (item) {
return item.EmployeeName //Name of property to be shown
},
source: dataSource.ttAdapter(),
suggestion: function (data) {
return '<div>' + data.EmployeeName + '–' + data.EmployeeID + '</div>'
}
});
}
catch (e) {
}
}
function FailureBindEmployeeTypeAhead() {
}

Create a reusable modal using JQuery

I know writing an IF-ELSEIF-ELSE statement in the loop below would work, however I want to avoid having to write multiple modals. Instead I am looking for a JQuery modal to pop up when the image icon (basically a info image) is clicked. I want to be able to pass in the error into the function, which will then display in the modal.
Example:
Say I have a 400 Error and 500 Error, when I click the info icon, the definition should appear.
CODE BELOW:
index.gsp
<html>
<%-- Some code (saving space for body) --%>
<body>
<div id="content">
<div id="content-header">
<h1>Error Checking</h1>
</div> <!-- #content-header -->
<div id="content-container">
<div class="portlet">
<div class="portlet-content">
<div class="table-responsive">
<table
class="table table-striped table-bordered table-hover table-highlight table-checkable"
data-provide="datatable"
data-display-rows="25"
data-info="true"
data-search="true"
data-length-change="true"
data-paginate="true">
<thead>
<tr>
<th data-filterable="true" data-sortable="true" data-direction="desc">User ID</th>
<th data-filterable="true" data-sortable="true" data-direction="desc">Task ID</th>
<th data-filterable="true" data-sortable="true" data-direction="desc">Error Message</th>
</tr>
</thead>
<tbody>
<g:each in="${lists}" var="list">
<tr>
<td>${list.userId}</td>
<td>${list.taskId}</td>
<td>
**%{--WANT TO PLACE MODAL CALL HERE--}%**
**<i class="fa fa-exclamation-triangle ui-popover pull-left" style="color:#f0ad4e;"></i>
${list.errorMsg}**
</td>
</tr>
</g:each>
</tbody>
</table>
</div> <!-- /.table-responsive -->
</div> <!-- /.portlet-content -->
</div> <!-- /.portlet -->
</div> <!-- /#content-container -->
</div> <!-- #content -->
The MODAL I want to pop up:
<div id="styledFreqLargerModal" class="modal modal-styled fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 class="modal-title">Issue</h3>
</div>
<div class="modal-body">
</div>
<div class="modal-footer">
<button type="button" class="btn btn-tertiary" data-dismiss="modal">Close</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div><!-- /.modal -->
You can generate dynamic id's using your list item's id. Then you can place your modal at the place you have mentioned. The following is a code example:
<div id="styledFreqLargerModal${list.id}" class="modal modal-styled fade">
[..]
</div><!-- /.modal -->
If you are using jQuery-UI
<a class="openDialog" href="#styledFreqLargerModal${list.id}"><i class="fa fa-exclamation-triangle ui-popover pull-left" style="color:#f0ad4e;"></i></a>
In your javascript do:
$(document).on("click", "a.openDialog", function() {
$($(this).attr("href")).dialog();
}
If you are using bootstrap
<a data-toggle="modal" href="#styledFreqLargerModal${list.id}"><i class="fa fa-exclamation-triangle ui-popover pull-left" style="color:#f0ad4e;"></i></a>
Solved the problem... Used Jquery modal. This prevented me from having to create multiple modals. In the modal I have a "click" method that determines which item got clicked, then outputs that specific message. See code below.
index.gsp
<html>
<%-- Some code (saving space for body) --%>
<body>
<div id="content">
<div id="content-header">
<h1>Error Checking</h1>
</div> <!-- #content-header -->
<div id="content-container">
<div class="portlet">
<div class="portlet-content">
<div class="table-responsive">
<table
class="table table-striped table-bordered table-hover table-highlight table-checkable"
data-provide="datatable"
data-display-rows="25"
data-info="true"
data-search="true"
data-length-change="true"
data-paginate="true">
<thead>
<tr>
<th data-filterable="true" data-sortable="true" data-direction="desc">User ID</th>
<th data-filterable="true" data-sortable="true" data-direction="desc">Task ID</th>
<th data-filterable="true" data-sortable="true" data-direction="desc">Error Message</th>
</tr>
</thead>
<tbody>
<g:each in="${lists}" var="list">
<tr>
<td>${list.userId}</td>
<td>${list.taskId}</td>
<td>
<g:if test="${(list.errorMsg).contains("400")}">
<a id="modalAlert-${list.taskId}" class="modal-alert-null" ><i class="fa fa-exclamation-triangle ui-popover pull-left" style="color:#f0ad4e;"></i></a>
${list.errorMsg}
</g:if>
<g:elseif test="${(list.errorMsg).contains("500")}">
<a id="modalAlert-${list.taskId}" class="modal-alert-outOfBounds" ><i class="fa fa-exclamation-triangle ui-popover pull-left" style="color:#f0ad4e;"></i></a>
${list.errorMsg}
</g:elseif>
</td>
</tr>
</g:each>
</tbody>
</table>
</div> <!-- /.table-responsive -->
</div> <!-- /.portlet-content -->
</div> <!-- /.portlet -->
</div> <!-- /#content-container -->
</div> <!-- #content -->
<r:require modules="jquery"/>
<script type="text/javascript">
$(document).ready(function() {
// Null pointer exception
$(".modal-alert-null").click(function() {
modalAlert("400 error message");
});
// outOfBoundsException
$(".modal-alert-outOfBounds").click(function() {
modalAlert("500 error message");
});
});
function modalAlert(description)
{
$("body").append(buildAlertModal());
$("#alert-modal .modal-description").html(description);
$("#alert-modal").modal("show");
}
function buildAlertModal() {
return "<div id='alert-modal' class='modal modal-styled fade'>" +
" <div class='modal-dialog'>" +
" <div class='modal-content'>" +
" <div class='modal-header'>" +
" <button type='button' class='close' data-dismiss='modal' aria-hidden='true'>×</button>" +
" <h3 class='modal-titl'>Exception Info</h3>" +
" </div>" +
" <div class='modal-body'>" +
" <p class='modal-description'></p>" +
" </div>" +
" <div class='modal-footer'>" +
" <button type='button' class='btn btn-tertiary' data-dismiss='modal'>Close</button>" +
" </div>" +
" </div>" +
" </div>" +
"</div>";
}
function closeModalAlert() {
$("#alert-modal").modal("hide");
}
</script>

Categories