Laravel 9 passing data to Javascript file - laravel

I want to pass the data from the Laravel controller to the JS file then show it in the Laravel Blade view as it appears in the code
in this var dtUserTable = $('.user-list-table'),
user-list-table is a class that is called on the blade.php page. As it appears this is the call of it, how can I return the data from or pass the data from the Laravel controller to the JS file then show it in the blade.php file?
app-user-list.js
$(function () {
'use strict';
var dtUserTable = $('.user-list-table'),
newUserSidebar = $('.new-user-modal'),
newUserForm = $('.add-new-user'),
statusObj = {
1: { title: 'Pending', class: 'badge-light-warning' },
2: { title: 'Active', class: 'badge-light-success' },
3: { title: 'Inactive', class: 'badge-light-secondary' }
};
var assetPath = '../../../app-assets/',
userView = 'app-user-view.html',
userEdit = 'app-user-edit.html';
if ($('body').attr('data-framework') === 'laravel') {
assetPath = $('body').attr('data-asset-path');
userView = assetPath + 'app/user/view';
userEdit = assetPath + 'app/user/edit';
}
// Users List datatable
if (dtUserTable.length) {
dtUserTable.DataTable({
ajax: assetPath + 'data/user-list.json', // JSON file to add data
columns: [
// columns according to JSON
{ data: 'responsive_id' },
{ data: 'full_name' },
{ data: 'email' },
{ data: 'role' },
{ data: 'current_plan' },
{ data: 'status' },
{ data: '' }
],
columnDefs: [
{
// For Responsive
className: 'control',
orderable: false,
responsivePriority: 2,
targets: 0
},
{
// User full name and username
targets: 1,
responsivePriority: 4,
render: function (data, type, full, meta) {
var $name = full['full_name'],
$uname = full['username'],
$image = full['avatar'];
if ($image) {
// For Avatar image
var $output =
'<img src="' + assetPath + 'images/avatars/' + $image + '" alt="Avatar" height="32" width="32">';
} else {
// For Avatar badge
var stateNum = Math.floor(Math.random() * 6) + 1;
var states = ['success', 'danger', 'warning', 'info', 'dark', 'primary', 'secondary'];
var $state = states[stateNum],
$name = full['full_name'],
$initials = $name.match(/\b\w/g) || [];
$initials = (($initials.shift() || '') + ($initials.pop() || '')).toUpperCase();
$output = '<span class="avatar-content">' + $initials + '</span>';
}
var colorClass = $image === '' ? ' bg-light-' + $state + ' ' : '';
// Creates full output for row
var $row_output =
'<div class="d-flex justify-content-left align-items-center">' +
'<div class="avatar-wrapper">' +
'<div class="avatar ' +
colorClass +
' mr-1">' +
$output +
'</div>' +
'</div>' +
'<div class="d-flex flex-column">' +
'<a href="' +
userView +
'" class="user_name text-truncate"><span class="font-weight-bold">' +
$name +
'</span></a>' +
'<small class="emp_post text-muted">#' +
$uname +
'</small>' +
'</div>' +
'</div>';
return $row_output;
}
},
{
// User Role
targets: 3,
render: function (data, type, full, meta) {
var $role = full['role'];
var roleBadgeObj = {
Subscriber: feather.icons['user'].toSvg({ class: 'font-medium-3 text-primary mr-50' }),
Author: feather.icons['settings'].toSvg({ class: 'font-medium-3 text-warning mr-50' }),
Maintainer: feather.icons['database'].toSvg({ class: 'font-medium-3 text-success mr-50' }),
Editor: feather.icons['edit-2'].toSvg({ class: 'font-medium-3 text-info mr-50' }),
Admin: feather.icons['slack'].toSvg({ class: 'font-medium-3 text-danger mr-50' })
};
return "<span class='text-truncate align-middle'>" + roleBadgeObj[$role] + $role + '</span>';
}
},
{
// User Status
targets: 5,
render: function (data, type, full, meta) {
var $status = full['status'];
return (
'<span class="badge badge-pill ' +
statusObj[$status].class +
'" text-capitalized>' +
statusObj[$status].title +
'</span>'
);
}
},
{
// Actions
targets: -1,
title: 'Actions',
orderable: false,
render: function (data, type, full, meta) {
return (
'<div class="btn-group">' +
'<a class="btn btn-sm dropdown-toggle hide-arrow" data-toggle="dropdown">' +
feather.icons['more-vertical'].toSvg({ class: 'font-small-4' }) +
'</a>' +
'<div class="dropdown-menu dropdown-menu-right">' +
'<a href="' +
userView +
'" class="dropdown-item">' +
feather.icons['file-text'].toSvg({ class: 'font-small-4 mr-50' }) +
'Details</a>' +
'<a href="' +
userEdit +
'" class="dropdown-item">' +
feather.icons['archive'].toSvg({ class: 'font-small-4 mr-50' }) +
'Edit</a>' +
'<a href="javascript:;" class="dropdown-item delete-record">' +
feather.icons['trash-2'].toSvg({ class: 'font-small-4 mr-50' }) +
'Delete</a></div>' +
'</div>' +
'</div>'
);
}
}
],
order: [[2, 'desc']],
dom:
'<"d-flex justify-content-between align-items-center header-actions mx-1 row mt-75"' +
'<"col-lg-12 col-xl-6" l>' +
'<"col-lg-12 col-xl-6 pl-xl-75 pl-0"<"dt-action-buttons text-xl-right text-lg-left text-md-right text-left d-flex align-items-center justify-content-lg-end align-items-center flex-sm-nowrap flex-wrap mr-1"<"mr-1"f>B>>' +
'>t' +
'<"d-flex justify-content-between mx-2 row mb-1"' +
'<"col-sm-12 col-md-6"i>' +
'<"col-sm-12 col-md-6"p>' +
'>',
language: {
sLengthMenu: 'Show _MENU_',
search: 'Search',
searchPlaceholder: 'Search..'
},
// Buttons with Dropdown
buttons: [
{
text: 'Add New User',
className: 'add-new btn btn-primary mt-50',
attr: {
'data-toggle': 'modal',
'data-target': '#modals-slide-in'
},
init: function (api, node, config) {
$(node).removeClass('btn-secondary');
}
}
],
// For responsive popup
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function (row) {
var data = row.data();
return 'Details of ' + data['full_name'];
}
}),
type: 'column',
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table',
columnDefs: [
{
targets: 2,
visible: false
},
{
targets: 3,
visible: false
}
]
})
}
},
language: {
paginate: {
// remove previous & next text from pagination
previous: ' ',
next: ' '
}
},
initComplete: function () {
// Adding role filter once table initialized
this.api()
.columns(3)
.every(function () {
var column = this;
var select = $(
'<select id="UserRole" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Role </option></select>'
)
.appendTo('.user_role')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding plan filter once table initialized
this.api()
.columns(4)
.every(function () {
var column = this;
var select = $(
'<select id="UserPlan" class="form-control text-capitalize mb-md-0 mb-2"><option value=""> Select Plan </option></select>'
)
.appendTo('.user_plan')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append('<option value="' + d + '" class="text-capitalize">' + d + '</option>');
});
});
// Adding status filter once table initialized
this.api()
.columns(5)
.every(function () {
var column = this;
var select = $(
'<select id="FilterTransaction" class="form-control text-capitalize mb-md-0 mb-2xx"><option value=""> Select Status </option></select>'
)
.appendTo('.user_status')
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex($(this).val());
column.search(val ? '^' + val + '$' : '', true, false).draw();
});
column
.data()
.unique()
.sort()
.each(function (d, j) {
select.append(
'<option value="' +
statusObj[d].title +
'" class="text-capitalize">' +
statusObj[d].title +
'</option>'
);
});
});
}
});
}
// Check Validity
function checkValidity(el) {
if (el.validate().checkForm()) {
submitBtn.attr('disabled', false);
} else {
submitBtn.attr('disabled', true);
}
}
// Form Validation
if (newUserForm.length) {
newUserForm.validate({
errorClass: 'error',
rules: {
'user-fullname': {
required: true
},
'user-name': {
required: true
},
'user-email': {
required: true
}
}
});
newUserForm.on('submit', function (e) {
var isValid = newUserForm.valid();
e.preventDefault();
if (isValid) {
newUserSidebar.modal('hide');
}
});
}
// To initialize tooltip with body container
$('body').tooltip({
selector: '[data-toggle="tooltip"]',
container: 'body'
});
});
Blade/View
#extends('panel.index')
#section('css-con')
<!-- BEGIN: Vendor CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/dataTables.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/responsive.bootstrap4.min.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/vendors/css/tables/datatable/buttons.bootstrap4.min.css')}}">
<!-- END: Vendor CSS-->
<!-- BEGIN: Page CSS-->
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/plugins/forms/form-validation.css')}}">
<link rel="stylesheet" type="text/css" href="{{asset('app-assets/css/pages/app-user.css')}}">
<!-- END: Page CSS-->
#endsection
#section('content')
<!-- users list start -->
<section class="app-user-list">
<!-- users filter start -->
<div class="card">
<h5 class="card-header">Search Filter</h5>
<div class="d-flex justify-content-between align-items-center mx-50 row pt-0 pb-2">
<div class="col-md-4 user_role"></div>
<div class="col-md-4 user_plan"></div>
<div class="col-md-4 user_status"></div>
</div>
</div>
<!-- users filter end -->
<!-- list section start -->
<div class="card">
<div class="card-datatable table-responsive pt-0">
<table class="user-list-table table">
<thead class="thead-light">
<tr>
<th></th>
<th>User</th>
<th>Email</th>
<th>Role</th>
<th>Plan</th>
<th>Status</th>
<th>Actions</th>
</tr>
</thead>
</table>
</div>
<!-- Modal to add new user starts-->
<div class="modal modal-slide-in new-user-modal fade" id="modals-slide-in">
<div class="modal-dialog">
<form class="add-new-user modal-content pt-0">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>
<div class="modal-header mb-1">
<h5 class="modal-title" id="exampleModalLabel">New User</h5>
</div>
<div class="modal-body flex-grow-1">
<div class="form-group">
<label class="form-label" for="basic-icon-default-fullname">Full Name</label>
<input type="text" class="form-control dt-full-name" id="basic-icon-default-fullname" placeholder="John Doe" name="user-fullname" aria-label="John Doe" aria-describedby="basic-icon-default-fullname2" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-uname">Username</label>
<input type="text" id="basic-icon-default-uname" class="form-control dt-uname" placeholder="Web Developer" aria-label="jdoe1" aria-describedby="basic-icon-default-uname2" name="user-name" />
</div>
<div class="form-group">
<label class="form-label" for="basic-icon-default-email">Email</label>
<input type="text" id="basic-icon-default-email" class="form-control dt-email" placeholder="john.doe#example.com" aria-label="john.doe#example.com" aria-describedby="basic-icon-default-email2" name="user-email" />
<small class="form-text text-muted"> You can use letters, numbers & periods </small>
</div>
<div class="form-group">
<label class="form-label" for="user-role">User Role</label>
<select id="user-role" class="form-control">
<option value="subscriber">Subscriber</option>
<option value="editor">Editor</option>
<option value="maintainer">Maintainer</option>
<option value="author">Author</option>
<option value="admin">Admin</option>
</select>
</div>
<button type="submit" class="btn btn-primary mr-1 data-submit">Submit</button>
<button type="reset" class="btn btn-outline-secondary" data-dismiss="modal">Cancel</button>
</div>
</form>
</div>
</div>
<!-- Modal to add new user Ends-->
</div>
<!-- list section end -->
</section>
<!-- users list ends -->
#endsection
#section('jc-con')
<!-- BEGIN: Page Vendor JS-->
<script src="{{asset('app-assets/vendors/js/tables/datatable/jquery.dataTables.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/dataTables.responsive.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/responsive.bootstrap4.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/datatables.buttons.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/tables/datatable/buttons.bootstrap4.min.js')}}"></script>
<script src="{{asset('app-assets/vendors/js/forms/validation/jquery.validate.min.js')}}"></script>
<!-- END: Page Vendor JS-->
<!-- BEGIN: Page JS-->
<script src="{{asset('app-assets/js/scripts/pages/app-user-list.js')}}"></script>
<!-- END: Page JS-->
#endsection
Below is the function that I call when I want to get the data in the Laravel controller.
public function list()
{
$data = DB::table('users')->get();
return view('content.apps.user.user-list',compact('data'));
}

blade
#push('scripts')
<script>
//line chart
var line = new Morris.Line({
element: 'line-chart',
resize: true,
data: [
#foreach ($data as $value)
{
ym: "{{ $value->year }}-{{ $value->month }}", sum: "{{ $value->sum }}"
},
#endforeach
],
xkey: 'ym',
ykeys: ['sum'],
labels: ['#lang('site.total')'],
lineWidth: 2,
gridTextFamily: 'Open Sans',
gridTextSize: 10
});
</script>
#endpush

Related

I want to show data on chart bar when I search by date wise using Laravel

I have chart bar and I am trying to show data by date wise when I filter by date but unfortunately data does not show on chart bar. I want that when I select a start date and end date record should be shown on chart bar by date wise.
Controller
public function status(Request $request)
{
$date = explode(' - ', $request->date);
$manager_hourlog = Hourlog::with('project', "user")->whereBetween('date', $date)
->get()
->groupBy('project.name');
$projects = [];
$totals = [];
foreach ($manager_hourlog as $key => $val) {
$projects[] = $key;
}
foreach ($manager_hourlog as $key2 => $val) {
$minutes = $val->sum('hour_work');
$totals[] = round($minutes / 60, 1);
}
$users = User::where("status", 1)->get();
$data = [
// manager report
'manager_projects' => $projects,
'totals' => $totals,
"manager_hourlog" => $manager_hourlog,
];
return $data;
return response()->json($data, 200);
}
html view
<form action="{{route('dashboard')}}" method="post" >
<div class="form-group">
<div class="input-group theme-input-group select-max-h-200">
<div class="input-group-prepend width-160px">
<div class="input-group-text">Date
</div>
</div>
<input parsley-trigger="change" required type="text" id="date" class="form-control" name="date" autocomplete="off">
<div class="input-group-append">
<span class="input-group-text">
<i class="md md-event-note">
</i>
</span>
</div>
</div>
<!-- input-group -->
</div>
</div>
<div class="col-lg-1">
<div class="text-right">
<button class="btn btn-light-theme waves-effect waves-light" id="search" name="search" type="submit">
<i class="fa fa-search pr-1">
</i> Search
</button>
</div>
</div>
</form>
script
<script type="text/javascript">
$(function () {
$('#search').on('click', function () {
var date = $("#date").val();
$.ajax({
type: 'GET',
url: '{{Route("dashboard.status")}}',
data: {
date: date
},
dataType: "JSon",
success: function(response){
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db", "#9b59b6", "#34495e", "#16a085", "#27ae60", "#2980b9", "#8e44ad", "#2c3e50", "#f1c40f", "#e67e22", "#e74c3c", "#ecf0f1", "#95a5a6", "#f39c12", "#d35400", "#c0392b", "#bdc3c7", "#7f8c8d"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: {!! json_encode($manager_projects) !!},
datasets: [
#foreach($users as $user)
{
label: {!! json_encode($user->name) !!},
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
data: [
#foreach($manager_hourlog as $hourlog)
{{$hourlog->where("user_id", $user->id)->sum("hour_work") / 60}},
#endforeach
]
},
#endforeach
]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Project Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
console.log(response);
},
error: function(xhr){
console.log(xhr.responseText);
}});
});
});
</script>

Asp.Net Mvc Html.BeginFormSubmit ajax sends twice request (one's type xhr the other's document)

I am working on a survey application with Asp.Net MVC. I have a page named Index.cshtml which has a question table and a 'Add New' button.Once button clicked, a popup is opened with jQuery. I am calling a view from controller to fill jQuery dialog named as AddOrEdit.cshtml (child page). I am adding new question and options. Question is a textfield and its options are added in editable table. Once clicked submt button Submit form event (save or update) is fired. But ajax sends twice request. One of these requests send empty object, the other sends full object. Where am I making a mistake?
According to my research, what causes this problem is that the unobtrusive validator is placed on 2 different pages. But this is not the case for me.
When I debug with chrome in f12, the initiator of one of the 2 requests 'jquery' the initiator of the other 'other' The type of one of these 2 post requests appears as 'XHR' and the type of the other is 'document'.
Index.cshtml
#{
ViewBag.Title = "Soru Listesi";
}
<h2>Soru Oluşturma</h2>
<a class="btn btn-success" style="margin-bottom: 10px"
onclick="PopupForm('#Url.Action("AddOrEdit","Question")')"><i class="fa fa-plus"></i> Yeni Soru Oluştur</a><table id="questionTable" class="table table-striped table-bordered accent-blue" style="width: 100%">
<thead>
<tr>
<th>Soru No</th>
<th>Soru Adı</th>
<th>Oluşturma Tarihi</th>
<th>Güncelleme Tarihi</th>
<th>Güncelle/Sil</th>
</tr>
</thead>
</table>
<link
href="https://cdn.datatables.net/1.10.20/css/dataTables.bootstrap4.min.css" rel="stylesheet" />
<link href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet" />
#section Scripts{
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.20/js/dataTables.bootstrap4.min.js"></script>
<script>
var Popup, dataTable;
$(document).ready(function() {
dataTable = $("#questionTable").DataTable({
"ajax": {
"url": "/Question/GetData",
"type": "GET",
"datatype": "json"
},
"columnDefs": [
{ targets: 2 }
],
"scrollX": true,
"scrollY": "auto",
"columns": [
{ "data": "QuestionId" },
{ "data": "QuestionName" },
{
"data": "CreatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "UpdatedDate",
"render": function(data) { return getDateString(data); }
},
{
"data": "QuestionId",
"render": function(data) {
return "<a class='btn btn-primary btn-sm' onclick=PopupForm('#Url.Action("AddOrEdit", "Question")/" +
data +
"')><i class='fa fa-pencil'></i> Güncelle</a><a class='btn btn-danger btn-sm' style='margin-left:5px' onclick=Delete(" +
data +
")><i class='fa fa-trash'></i> Sil</a>";
},
"orderable": false,
"searchable": false,
"width": "150px"
}
],
"language": {
"emptyTable":
"Soru bulunamadı, lütfen <b>Yeni Soru Oluştur</b> butonuna tıklayarak yeni soru oluşturunuz. "
}
});
});
function getDateString(date) {
var dateObj = new Date(parseInt(date.substr(6)));
let year = dateObj.getFullYear();
let month = (1 + dateObj.getMonth()).toString().padStart(2, '0');
let day = dateObj.getDate().toString().padStart(2, '0');
return day + '/' + month + '/' + year;
};
function PopupForm(url) {
var formDiv = $('<div/>');
$.get(url)
.done(function(response) {
formDiv.html(response);
Popup = formDiv.dialog({
autoOpen: true,
resizable: true,
title: 'Soru Detay',
modal: true,
height: 'auto',
width: '700',
close: function() {
Popup.dialog('destroy').remove();
}
});
});
}
function SubmitForm(form) {
debugger;
if (form.checkValidity() === false) {
debugger;
event.preventDefault();
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}
function ResetForm(form) {
Popup.dialog('close');
return false;
}
function Delete(id) {
if (confirm('Bu soruyu silmek istediğinizden emin misiniz?')) {
$.ajax({
type: "POST",
url: '#Url.Action("Delete", "Question")/' + id,
success: function(data) {
if (data.success) {
dataTable.ajax.reload();
$.notify(data.message,
{
className: "success",
globalPosition: "top center",
title: "BAŞARILI"
})
}
}
});
}
}
</script>
}
AddOrEdit.cshtml
#using MerinosSurvey.Models
#model Questions
#{
Layout = null;
}
#using (Html.BeginForm("AddOrEdit", "Question", FormMethod.Post, new { #class = "needs-validation",
novalidate = "true", onsubmit = "return SubmitForm(this)", onreset = "return ResetForm(this)", id =
"questionForm" }))
{
<div class="form-group row">
#Html.Label("QuestionId", "Soru No", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.TextBoxFor(model => model.QuestionId, new { #readonly = "readonly", #class = "form-control" })
</div>
</div>
<div class="form-group row">
#Html.Label("QuestionName", "Soru Adı", new { #class = "col-form-label col-md-3" })
<div class="col-md-9">
#Html.EditorFor(model => model.QuestionName, new { htmlAttributes = new { #class = "form-control", required = "true" } })
<div class="valid-feedback"><i class="fa fa-check">Süpersin</i></div>
<div class="invalid-feedback "><i class="fa fa-times"></i></div>
</div>
</div>
#*<div class="form-group row">
#Html.LabelFor(model => model.CreatedDate, new { #class = "form-control-label col-md-3"})
<div class="col-md-9">
#Html.EditorFor(model => model.CreatedDate, "{0:yyyy-MM-dd}", new { htmlAttributes = new { #class = "form-control", type = "date", #readonly = "readonly",required="false" } })
</div>
</div>*#
<div class="table-wrapper form-group table-responsive-md">
<div class="table-title">
<div class="form-group row">
<div class="col-md-9">Seçenekler</div>
<div class="col-md-3">
<a class="btn btn-success add-new" style="margin-bottom: 10px"><i class="fa fa-plus"></i>Seçenek Ekle</a>
</div>
</div>
</div>
<table class="table optionTable">
<thead>
<tr>
<th scope="col">Seçenek Id</th>
<th scope="col">Seçenek Adı</th>
<th scope="col">Güncelle/Sil</th>
</tr>
</thead>
<tbody>
#*#foreach (Options options in Model.Options)
{
<tr>
<td>#options.OptionId</td>
<td>#options.OptionName</td>
<td>
<a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip">
<i class="fa fa-check">Onayla</i></a>
<a class="edit btn btn-secondary btn-sm" title="Edit" data-toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>
<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>
</td>
</tr>
}*#
</tbody>
</table>
</div>
<div class="form-group row">
<input type="submit" value="Submit" class="btn btn-primary" id="btnSubmit" />
<input type="reset" value="Reset" class="btn btn-secondary" />
</div>
}
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip();
//var actions = $("table.optionTable td:last-child").html();
var actions =' <a class="add btn btn-primary btn-sm" title="Add" data-toggle="tooltip"><i
class="fa fa-check">Onayla</i></a>' + '<a class="edit btn btn-secondary btn-sm" title="Edit" data toggle="tooltip"><i class="fa fa-pencil">Güncelle</i></a>' +'<a class="delete btn-danger btn-sm" title="Delete" data-toggle="tooltip"><i class="fa fa-trash">Sil</i></a>';
// Append table with add row form on add new button click
$(".add-new").click(function () {
$(this).attr("disabled", "disabled");
var index = $("table.optionTable tbody tr:last-child").index();
var row = '<tr>' +
'<td><input type="text" class="form-control" name="optionId" id="optionId"></td>' +
'<td><input type="text" class="form-control" name="optionId" id="optionName"></td>' +
'<td>' + actions + '</td>' +
'</tr>';
$("table.optionTable").append(row);
$("table.optionTable tbody tr").eq(index + 1).find(".add, .edit").toggle();
$('[data-toggle="tooltip"]').tooltip();
});
// Add row on add button click
$(document).on("click", ".add", function () {
var empty = false;
var input = $(this).parents("tr").find('input[type="text"]');
input.each(function () {
if (!$(this).val()) {
$(this).addClass("error");
empty = true;
} else {
$(this).removeClass("error");
}
});
$(this).parents("tr").find(".error").first().focus();
if (!empty) {
input.each(function () {
$(this).parent("td").html($(this).val());
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").removeAttr("disabled");
}
});
// Edit row on edit button click
$(document).on("click", ".edit", function () {
$(this).parents("tr").find("td:not(:last-child)").each(function () {
$(this).html('<input type="text" class="form-control" value="' + $(this).text() + '">');
});
$(this).parents("tr").find(".add, .edit").toggle();
$(".add-new").attr("disabled", "disabled");
});
// Delete row on delete button click
$(document).on("click", ".delete", function () {
debugger;
$(this).parents("tr").remove();
$(".add-new").removeAttr("disabled");
});
});
event.preventDefault(); move this line and place it immediately after function SubmitForm (form){
Like below:
function SubmitForm(form) {
debugger;
event.preventDefault();
if (form.checkValidity() === false) {
debugger;
event.stopPropagation();
}
form.classList.add('was-validated');
if ($(form).valid()) {
var question = {};
question.questionId = 1111;
var options = new Array();
$("#questionForm TBODY TR").each(function() {
var row = $(this);
var option = {};
option.OptionId = row.find("TD").eq(0).html();
option.OptionName = row.find("TD").eq(1).html();
options.push(option);
});
question.options = options;
question.responses = new Array();
$.ajax({
type: "POST",
url: form.action,
data: JSON.stringify(question),
success: function(data) {
if (data.success) {
debugger;
Popup.dialog('close');
dataTable.ajax.reload();
$.notify(data.message,
{
globalPosition: "top center",
className: "success",
showAnimation: "slideDown",
gap: 1000
});
}
},
error: function(req, err) {
debugger;
alert('req : ' + req + ' err : ' + err.data);
},
complete: function(data) {
alert('complete : ' + data.status);
}
});
}
}

How to calculate two input values and put the result in another variable?

I have Button A and Button B, When these buttons get clicked I'm getting
two input boxes with some value I want to store a total of these two input boxes and also want their label gets created dynamically
<template>
<div> <form type="get" action="/asd">
<div>
<label>Add A</label>
<button type="button" #click="addRow">100</button>
</div>
<div> <label>Add B</label>
<button type="button" #click="addRow1">200</button>
</div>
<div v-for="row in rows" :key="row.id">
<button-counter :name ="row.name" :id="row.id" :value="row.value"></button-counter>
</div> <div>total = ?</div>
<button>submit</button>
</form>
</div>
<script type="text/javascript">
Vue.component("button-counter", {
props: {
value: {
default: ""
}
},
template: '<input name=row.name type="text" style="margin-top: 10px;" v-model="value" >'
});
export default {
data() {
return {
rows: [],
count: 0
};
},
methods: {
addRow: function() {
var txtCount = 1;
let id = "txt_" + txtCount;
this.rows.push({ name:'A',value:100, description: "textbox1", id });
},
addRow1: function() {
var txtCount = 1;
let id = "txt2_" + txtCount;
this.rows.push({name:'B',value:200, description: "textbox2", id });
}
}
};

VUE.JS template not showing up

I have created a template for chat module. It was working fine yesterday but today there were some issues in some npm module so I ran the command npm audit fix --force and after that command is finished my chat template or any VUE template stops working means it is not showing up.
Here is the code of my template.
<template>
<div>
<div class="row">
<div class="col-md-12">
<div class="panel panel-primary">
<div class="panel-heading">
<span class="glyphicon glyphicon-comment"></span> Chat with {{ withUser.name }}
<button class="btn btn-warning btn-sm pull-right" #click="startVideoCallToUser(withUser.id)" type="button">
<span class="fa fa-video-camera"></span> Video Call
</button>
</div>
<div class="panel-body">
<ul class="chat" v-chat-scroll>
<li class="clearfix" v-for="message in messages" v-bind:class="{ 'right' : check(message.sender.id), 'left' : !check(message.sender.id) }">
<span class="chat-img" v-bind:class="{ 'pull-right' : check(message.sender.id) , 'pull-left' : !check(message.sender.id) }">
<img :src="'http://placehold.it/50/FA6F57/fff&text='+ message.sender.name" alt="User Avatar" class="img-circle" />
</span>
<div class="chat-body clearfix">
<div class="header">
<small class=" text-muted"><span class="glyphicon glyphicon-time"></span><timeago :since="message.created_at" :auto-update="10"></timeago></small>
<strong v-bind:class="{ 'pull-right' : check(message.sender.id) , 'pull-left' : !check(message.sender.id)}" class="primary-font">
{{ message.sender.name }}
</strong>
</div>
<p v-bind:class="{ 'pull-right' : check(message.sender.id) , 'pull-left' : !check(message.sender.id)}">
{{ message.text }}
</p>
<div class="row">
<div class="col-md-3" v-for="file in message.files">
<img :src="file.file_details.webPath" alt="" class="img-responsive">
<a :href="file.file_details.webPath" target="_blank" download>Download - {{ file.name }}</a>
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="panel-footer">
<div class="input-group">
<input id="btn-input" type="text" v-model="text" class="form-control input-sm" placeholder="Type your message here..." />
<span class="input-group-btn">
<button class="btn btn-warning btn-sm" type="button" #click.prevent="send()" id="btn-chat">
Send
</button>
</span>
</div>
<div class="input-group">
<input type="file" multiple class="form-control">
<span class="input-group-btn">
<button class="btn btn-warning btn-sm" type="button" #click.prevent="sendFiles()">
Send Files
</button>
</span>
</div>
</div>
</div>
</div>
<div class="col-md-6 d-flex justify-center">
<video-section></video-section>
</div>
<div id="incomingVideoCallModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Incoming Call</h4>
</div>
<div class="modal-footer">
<button type="button" id="answerCallButton" class="btn btn-success">Answer</button>
<button type="button" id="denyCallButton" data-dismiss="modal" class="btn btn-danger">Deny</button>
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-3" v-for="file in conversation.files">
<img :src="file.file_details.webPath" alt="" class="img-responsive">
<a :href="file.file_details.webPath" target="_blank" download>Download - {{ file.name }}</a>
</div>
</div>
</div>
</template>
<script>
$(function () {
var localVideo = document.getElementById('localVideo');
var remoteVideo = document.getElementById('remoteVideo');
var answerButton = document.getElementById('answerCallButton');
answerButton.onclick = answerCall;
$('input[type=file]').on('change', prepareUpload);
});
var files;
var conversationID;
var luid;
var ruid;
var startTime;
var localStream;
var pc;
var offerOptions = {
offerToReceiveAudio: 1,
offerToReceiveVideo: 1
};
var isCaller = false;
var peerConnectionDidCreate = false;
var candidateDidReceived = false;
export default {
props: ['conversation' , 'currentUser'],
data() {
return {
conversationId : this.conversation.conversationId,
channel : this.conversation.channel_name,
messages : this.conversation.messages,
withUser : this.conversation.user,
text : '',
constraints : {
audio: false,
video: true
},
}
},
methods: {
startVideoCallToUser (id) {
Cookies.set('remoteUUID', id);
window.remoteUUID = id;
luid = Cookies.get('uuid');
ruid = Cookies.get('remoteUUID');
isCaller = true;
start()
},
check(id) {
return id === this.currentUser.id;
},
send() {
var self = this;
axios.post('/chat/message/send',{
conversationId : this.conversationId,
text: this.text,
}).then((response) => {
this.listenForNewMessage();
self.text = '';
});
},
sendFiles() {
var data = new FormData();
$.each(files, function(key, value)
{
data.append('files[]', value);
});
data.append('conversationId' , this.conversationId);
axios.post('/chat/message/send/file', data);
},
listenForNewMessage: function () {
Echo.join(this.channel)
.here((users) => {
console.log(users)
})
.listen('\\PhpJunior\\LaravelVideoChat\\Events\\NewConversationMessage', (data) => {
var self = this;
if ( data.files.length > 0 ){
$.each( data.files , function( key, value ) {
self.conversation.files.push(value);
});
}
this.messages.push(data);
})
.listen('\\PhpJunior\\LaravelVideoChat\\Events\\VideoChatStart', (data) => {
if(data.to != this.currentUser.id){
return;
}
if(data.type === 'signal'){
onSignalMessage(data);
}else if(data.type === 'text'){
console.log('received text message from ' + data.from + ', content: ' + data.content);
}else{
console.log('received unknown message type ' + data.type + ' from ' + data.from);
}
});
},
},
beforeMount () {
Cookies.set('uuid', this.currentUser.id);
Cookies.set('conversationID', this.conversationId);
},
mounted() {
this.listenForNewMessage();
}
}
function onSignalMessage(m){
console.log(m.subtype);
if(m.subtype === 'offer'){
console.log('got remote offer from ' + m.from + ', content ' + m.content);
Cookies.set('remoteUUID', m.from);
onSignalOffer(m.content);
}else if(m.subtype === 'answer'){
onSignalAnswer(m.content);
}else if(m.subtype === 'candidate'){
onSignalCandidate(m.content);
}else if(m.subtype === 'close'){
onSignalClose();
}else{
console.log('unknown signal type ' + m.subtype);
}
}
function onSignalClose() {
trace('Ending call');
pc.close();
pc = null;
closeMedia();
clearView();
}
function closeMedia(){
localStream.getTracks().forEach(function(track){track.stop();});
}
function clearView(){
localVideo.srcObject = null;
remoteVideo.srcObject = null;
}
function onSignalCandidate(candidate){
onRemoteIceCandidate(candidate);
}
function onRemoteIceCandidate(candidate){
trace('onRemoteIceCandidate : ' + candidate);
if(peerConnectionDidCreate){
addRemoteCandidate(candidate);
}else{
//remoteCandidates.push(candidate);
var candidates = Cookies.getJSON('candidate');
if(candidateDidReceived){
candidates.push(candidate);
}else{
candidates = [candidate];
candidateDidReceived = true;
}
Cookies.set('candidate', candidates);
}
}
function onSignalAnswer(answer){
onRemoteAnswer(answer);
}
function onRemoteAnswer(answer){
trace('onRemoteAnswer : ' + answer);
pc.setRemoteDescription(answer).then(function(){onSetRemoteSuccess(pc)}, onSetSessionDescriptionError);
}
function onSignalOffer(offer){
Cookies.set('offer', offer);
$('#incomingVideoCallModal').modal('show');
}
function answerCall() {
isCaller = false;
luid = Cookies.get('uuid');
ruid = Cookies.get('remoteUUID');
$('#incomingVideoCallModal').modal('hide');
start()
}
function gotStream(stream) {
trace('Received local stream');
localVideo.srcObject = stream;
localStream = stream;
call()
}
function start() {
trace('Requesting local stream');
navigator.mediaDevices.getUserMedia({
audio: true,
video: {
width: {
exact: 320
},
height: {
exact: 240
}
}
})
.then(gotStream)
.catch(function(e) {
alert('getUserMedia() error: ' + e.name);
});
}
function call() {
conversationID = Cookies.get('conversationID');
trace('Starting call');
startTime = window.performance.now();
var videoTracks = localStream.getVideoTracks();
var audioTracks = localStream.getAudioTracks();
if (videoTracks.length > 0) {
trace('Using video device: ' + videoTracks[0].label);
}
if (audioTracks.length > 0) {
trace('Using audio device: ' + audioTracks[0].label);
}
var configuration = { "iceServers": [{ "urls": "stun:stun.ideasip.com" }] };
pc = new RTCPeerConnection(configuration);
trace('Created local peer connection object pc');
pc.onicecandidate = function(e) {
onIceCandidate(pc, e);
};
pc.oniceconnectionstatechange = function(e) {
onIceStateChange(pc, e);
};
pc.onaddstream = gotRemoteStream;
pc.addStream(localStream);
trace('Added local stream to pc');
peerConnectionDidCreate = true;
if(isCaller) {
trace(' createOffer start');
trace('pc createOffer start');
pc.createOffer(
offerOptions
).then(
onCreateOfferSuccess,
onCreateSessionDescriptionError
);
}else{
onAnswer()
}
}
function onAnswer(){
var remoteOffer = Cookies.getJSON('offer');
pc.setRemoteDescription(remoteOffer).then(function(){onSetRemoteSuccess(pc)}, onSetSessionDescriptionError);
pc.createAnswer().then(
onCreateAnswerSuccess,
onCreateSessionDescriptionError
);
}
function onCreateAnswerSuccess(desc) {
trace('Answer from pc:\n' + desc.sdp);
trace('pc setLocalDescription start');
pc.setLocalDescription(desc).then(
function() {
onSetLocalSuccess(pc);
},
onSetSessionDescriptionError
);
conversationID = Cookies.get('conversationID');
var message = {from: luid, to:ruid, type: 'signal', subtype: 'answer', content: desc, time:new Date()};
axios.post('/trigger/' + conversationID , message );
}
function onSetRemoteSuccess(pc) {
trace(pc + ' setRemoteDescription complete');
applyRemoteCandidates();
}
function applyRemoteCandidates(){
var candidates = Cookies.getJSON('candidate');
for(var candidate in candidates){
addRemoteCandidate(candidates[candidate]);
}
Cookies.remove('candidate');
}
function addRemoteCandidate(candidate){
pc.addIceCandidate(candidate).then(
function() {
onAddIceCandidateSuccess(pc);
},
function(err) {
onAddIceCandidateError(pc, err);
});
}
function onIceCandidate(pc, event) {
if (event.candidate){
trace(pc + ' ICE candidate: \n' + (event.candidate ? event.candidate.candidate : '(null)'));
conversationID = Cookies.get('conversationID');
var message = {from: luid, to:ruid, type: 'signal', subtype: 'candidate', content: event.candidate, time:new Date()};
axios.post('/trigger/' + conversationID , message );
}
}
function onAddIceCandidateSuccess(pc) {
trace(pc + ' addIceCandidate success');
}
function onAddIceCandidateError(pc, error) {
trace(pc + ' failed to add ICE Candidate: ' + error.toString());
}
function onIceStateChange(pc, event) {
if (pc) {
trace(pc + ' ICE state: ' + pc.iceConnectionState);
console.log('ICE state change event: ', event);
}
}
function onCreateSessionDescriptionError(error) {
trace('Failed to create session description: ' + error.toString());
}
function onCreateOfferSuccess(desc) {
trace('Offer from pc\n' + desc.sdp);
trace('pc setLocalDescription start');
pc.setLocalDescription(desc).then(
function() {
onSetLocalSuccess(pc);
},
onSetSessionDescriptionError
);
conversationID = Cookies.get('conversationID');
var message = {from: luid, to:ruid, type: 'signal', subtype: 'offer', content: desc, time:new Date()};
axios.post('/trigger/' + conversationID , message );
}
function onSetLocalSuccess(pc) {
trace( pc + ' setLocalDescription complete');
}
function onSetSessionDescriptionError(error) {
trace('Failed to set session description: ' + error.toString());
}
function gotRemoteStream(e) {
if (remoteVideo.srcObject !== e.stream) {
remoteVideo.srcObject = e.stream;
trace('pc received remote stream');
}
}
function trace(arg) {
var now = (window.performance.now() / 1000).toFixed(3);
console.log(now + ': ', arg);
}
function prepareUpload(event)
{
files = event.target.files;
}
</script>
<style>
.chat
{
list-style: none;
margin: 0;
padding: 0;
}
.chat li
{
margin-bottom: 10px;
padding-bottom: 5px;
border-bottom: 1px dotted #B3A9A9;
}
.chat li.left .chat-body
{
margin-left: 60px;
}
.chat li.right .chat-body
{
margin-right: 60px;
}
.chat li .chat-body p
{
margin: 0;
color: #777777;
}
.panel .slidedown .glyphicon, .chat .glyphicon
{
margin-right: 5px;
}
.panel-body
{
overflow-y: scroll;
height: 250px;
}
::-webkit-scrollbar-track
{
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
background-color: #F5F5F5;
}
::-webkit-scrollbar
{
width: 12px;
background-color: #F5F5F5;
}
::-webkit-scrollbar-thumb
{
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
background-color: #555;
}
And This is how I am calling my template in my blade template.
#section('content')
<div class="container-fluid">
<chat-room :conversation="{{ $conversation }}" :current-user="{{ auth()->user() }}"></chat-room>
</div>
#endsection
There are no errors in my laravel-echo-server nor in redis server nor in npm but still it is not showing up. I have tried some solutions but none of them are working.
Any help regarding this issue will be appreciated. Thank you in advance.
Can you check in Chrome dev tools for Javascript errors?

How to refresh HTML after AJAX post

I have a site where guests can sign in via a modal form.
The solution I came up with is working but I feel like it's a dirty/insecure way to do it.
In the master layout, I load the partial view which contains the modal form.
when the user is authenticated I refresh the navbar to show the logged in username. That's the part where I'm kind of confused. Wouldn't it be possible to 'refresh' the navbar which is also a partial view.
login-modal.blade.php:
<div class="ui small modal" id="loginModal">
<div class="header">
Login
</div>
<div class="ui active dimmer" id="loader" style="display: none">
<div class="ui text loader">Loading</div>
</div>
<div class="content">
<div class="ui grid">
<div class="nine wide column centered">
{!! Form::open(array('route' => 'auth.login', 'method' => 'post','id'=>'formLogin','class' => 'ui large form')) !!}
<meta name="csrf_token" content="{{ csrf_token() }}"/>
<div class="field {!! $errors->has('password') ? 'error' : '' !!}">
<div class="ui left icon input">
<i class="user icon"></i>
{!! Form::text('username','',['name'=>'username','id'=>'username','class' => 'pd','placeholder'=>'Username']) !!}
</div>
{!! $errors->first('username', '<span class="ui text" id="" style="color: #bf4d4b">:message</span>') !!}
</div>
<div class="field {!! $errors->has('password') ? 'error' : '' !!}">
<div class="ui left icon input">
<i class="lock icon"></i>
{!! Form::password('password',['name'=>'password','id'=>'password','class' => '','placeholder'=>'Password']) !!}
</div>
{!! $errors->first('password', '<span class="ui text" id="" style="color: #bf4d4b">:message</span>') !!}
</div>
{!! Form::submit('Login',['id'=>'loginButton','class'=>'ui fluid large teal submit button']) !!}
<div class="ui error message"></div>
{!! Form::close() !!}
<div class="ui message">
No account? Sign Up
</div>
</div>
</div>
</div>
<div class="actions">
</div>
</div>
now the javascript in the same file:
<script>
$('#loginButton').click(function () {
$('#loginModal').modal(
{
blurring: true,
closable: true,
})
.modal('show');
});
$(document).ready(function () {
$('form#formLogin').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
timeout: 10000,
url: $('form#formLogin').attr('action'),
dataType: 'json',
data: $('form#formLogin').serialize(),
beforeSend: function (xhr) {
$('div#loader').show();
var token = $('meta[name="csrf_token"]').attr('content');
if (token) {
return xhr.setRequestHeader('X-CSRF-TOKEN', token);
}
},
complete: function () {
$('div#loader').hide();
},
success: function (data) {
if (data.success == false) {
var errors = data.errors; $('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
$.each(errors, function (field, errormsg) {
if (errormsg.length != 0) {
var currentField = $('#loginModal').find('#' + field);
var currentFieldSpan = $('#loginModal').find('#span' + field);
if (currentFieldSpan.length > 0) {
$('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
}
currentField.closest("div.field").removeClass("field").addClass("field error");
$("<span class='ui text' id='span" + field + "' style='color: #bf4d4b'>" + errormsg + "</span>").insertAfter(currentField.closest("div.ui.left.icon.input"));
}
});
if ((typeof data.locked != 'undefined') && data.locked.status == true) {
//BIDOUILLE pour disable le button login//
function enableLoginButton() {
$('#loginModal').find('#loginButton').removeClass('disabled');
}
//disable login button
$('#loginModal').find('#loginButton').addClass('disabled');
//after lockout time enable the login button again
setTimeout(enableLoginButton, (data.locked.remainingtime * 1000));
}
}
else if (data.success == true) {//authentication was successful
var cnt = '<div class="ui simple dropdown item">' +
'<img class="logo" src="{{ asset('images/food.png') }}" style="margin-right: 1em">' +
data.user['username'] +
' <i class="dropdown icon"></i>' +
'<div class="menu">' +
'<a class="item" href="#">Link Item</a>' +
'<a class="item" href="#">Link Item</a>' +
'<div class="divider"></div>' +
'<div class="header">Header Item</div>' +
'<div class="item">' +
'<i class="dropdown icon"></i>' +
'Sub Menu' +
'<div class="menu">' +
'<a class="item" href="#">Link Item</a>' +
'<a class="item" href="#">Link Item</a>' +
'</div>' +
'</div>' +
'<a class="item" href="#">Link Item</a>' +
'</div>' +
'</div>'
//remove the signin button
$('#navbartop .right .item').remove();
//add the dropdown with username
$('#navbartop .right').append(cnt);
//dissmis modal
$('#loginModal').modal().modal('hide');
}
},
error: function (xhr) {
var validationerrors = xhr.responseJSON;
$('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
$.each(validationerrors, function (field, errormsg) {
if (errormsg.length != 0) {
//select the field
var currentField = $('#loginModal').find('#' + field);
var currentFieldSpan = $('#loginModal').find('#span' + field);
if (currentFieldSpan.length > 0) {
$('#loginModal').find('div.field.error').removeClass("field error").addClass("field");
$('#loginModal').find('span').remove();
}
//apply 'field error' class to the closest div with 'field' class
currentField.closest("div.field").removeClass("field").addClass("field error");
//appends a span with red text and the validation error message
$("<span class='ui text' id='span" + field + "' style='color: #bf4d4b'>" + errormsg + "</span>").insertAfter(currentField.closest("div.ui.left.icon.input"));
}
});
}
});
return false;
});
});
</script>
AuthController.php:
protected function handleUserWasAuthenticated(Request $request, $throttles)
{
if ($throttles) {
$this->clearLoginAttempts($request);
}
if (method_exists($this, 'authenticated')) {
return $this->authenticated($request, Auth::guard($this->getGuard())->user());
}
//if user intended to access Logout() while not logged in, avoid instant redirect and logout
if (str_contains(redirect()->intended()->getTargetUrl(),'auth/logout')) {
return redirect()->route('home.index')->with('success', Auth::user()->username.' logged in successfully. ');
}
if($request->ajax())
{
return Response::json(['success' => true, 'errors' => '','user'=> Auth::user()]);
}
return redirect()->intended($this->redirectPath())->with('success', Auth::user()->username.' logged in successfully. ');
}
public function login(Request $request)
{
$this->validateLogin($request);
// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return $this->sendLockoutResponse($request);
}
$credentials = $this->getCredentials($request);
if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}
// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
if($request->ajax())
{
return Response::json(['success' => false, 'errors' =>
[$this->loginUsername() => $this->getFailedLoginMessage()]
]);
}
return $this->sendFailedLoginResponse($request);
}
protected function sendLockoutResponse(Request $request)
{
$seconds = app(RateLimiter::class)->availableIn(
$this->getThrottleKey($request)
);
if($request->ajax()) {
return Response::json(['success' => false,
'errors' =>
[$this->loginUsername() => $this->getLockoutErrorMessage($seconds)],
'locked' =>
['status'=>true, 'remainingtime'=>$seconds]]);
}
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getLockoutErrorMessage($seconds),
]);
}
I would wrap the navbar into a div like this:
<div id="ajax-nav">
<!-- Nav here -->
</div>
Then you can reload the navbar when your login response was successful:
$('#ajax-nav').load("some url that returns the html of the navbar");
Then you just need a route that leads to a Controller that can generate the navbar based on the user login state (logged in or guest).
With this procedure, you can completely replace the content of the navbar with a newly generated one after a specific event like your successful login or you could even set an interval to refresh the navbar - but that should not be needed in your case.
I guess you need to change this line:
'<img class="logo" src="{{ asset('images/food.png') }}" style="margin-right: 1em">'
For
'<img class="logo" src="{{ asset(\'images/food.png\') }}" style="margin-right: 1em">'
I hope it works ;)

Resources