I need your help. I have 5 forms on my PHP page and send the processing of the data without a submit button. I do this through sending data to my controller (store) that processes the data and returns the information I need to another page. The submission of the form is done by an AJAX function.
The problem is that now I need to get the information filled out by the user in the forms and by clicking on a button generate a PDF with the options marked by it. How could have two distinct actions within the same form? Necessary that the data be processed without submitting as it already does and after being processed you can click on a button that goes to another page.
Ajax Function:
function enviaForm(){
var url = $("#formulario").attr("action");
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "POST",
url: url,
data: $("#formulario").serialize(),
dataType: "json",
beforeSend: function(){
$('.ajax-loader').css("visibility", "visible");
},
success: function($retorno){
$("#inputLimCalculado").text ($retorno.limFinal);
$("#inputRisco1").text ($retorno.risco1);
$("#inputRisco2").text ($retorno.risco2);
$("#inputAuxCheqOuro").text ($retorno.auxCheqOuro);
$("#inputAuxCartaoEmp").text ($retorno.auxCartaoEmp);
preencherPortfolio();
},
error: function($retorno){
console.log($retorno);
},
complete: function(){
$('.ajax-loader').css("visibility", "hidden");
}
});
preencherPortfolio();
}
Form:
#extends('entidades.layout')
<header class="row">
#include('entidades.header')
</header>
#section('conteudo')
<div class="container">
<br>
{{ csrf_field()}}
<table class="table table-primary">
<tr>
<td>MCI: {{ $entidades->cd_cli}}</td>
<td>Entidade: {{$entidades->nome}}</td>
</tr>
<tr>
<td>Atividade: {{$entidades->nom_atv}}</td>
<td>Natureza: {{$entidades->nom_atv}}</td>
</tr>
</table>
<button class="btn btn-primary mb-2" type="button" onclick="window.location='{{ route('entidade.index') }}'">Voltar à Consulta</button>
</div>
<div class="container">
<button class="btn btn-primary" type="button" id="entidadeBtn">
Dados da Entidade
</button>
<button class="btn btn-primary collapsed" type="button" id="dirigente1Btn" onclick="validaFormEnt();">
Dirigente 1
</button>
<button class="btn btn-primary collapsed" type="button" id="dirigente2Btn">
Dirigente 2
</button>
<button class="btn btn-primary" type="button" id="portfolioBtn" onclick="validarDirigentes();">
Portfólio
</button>
<button class="btn btn-primary" type="button" id="parecerBtn">
Parecer
</button>
<!-- botão teste para o desenvolvedor -->
<button class="btn btn-primary" type="button" id="desenvBtn">
Desenvolvedor
</button>
<!-- enviar dados na controller store para o cálculo do modelo -->
<form method="post" action="{{ route('entidade.store') }}" name="form" id="formulario">
<input type="hidden" name="mci" value="{{$mci}}"/>
<meta name="csrf-token" content="{{ csrf_token() }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}"/>
<input type="hidden" name="cd_nat" value="{{$entidades->cd_nat}}"/>
<input type="hidden" name="nom_atv" value="{{$entidades->nom_atv}}"/>
<!-- Receber se os formulários foram preenchidos -->
<input type="hidden" name="entControle" id="entControle" value="{{ csrf_token() }}"/>
<input type="hidden" name="dirig1Controle" id="dirig1Controle" value="{{ csrf_token() }}"/>
<input type="hidden" name="dirig2Controle" id="dirig2Controle" value="{{ csrf_token() }}"/>
<!-- ////////////////////////////////////////////////////////////////////// -->
<!-- //////Formulário da entidade////////////////////////////////////////// -->
<!-- ////////////////////////////////////////////////////////////////////// -->
<div id="entidadesToggle" style="display:none;">
#include('entidades.entidade')
</div>
<!-- ////////////////////////////////////////////////////////////////////// -->
<!-- /////////Formulário do dirigente 1//////////////////////////////////// -->
<!-- ////////////////////////////////////////////////////////////////////// -->
<div id="dirigente1Toggle" style="display:none;">
#include('entidades.dirigente1')
</div>
<!-- ////////////////////////////////////////////////////////////////////// -->
<!-- /////////Formulário do dirigente 2//////////////////////////////////// -->
<!-- ////////////////////////////////////////////////////////////////////// -->
<div id="dirigente2Toggle" style="display:none;">
#include('entidades.dirigente2')
</div>
<!-- ////////////////////////////////////////////////////////////////////// -->
<!-- /////////////////////////////////Portfólio//////////////////////////// -->
<!-- ////////////////////////////////////////////////////////////////////// -->
<div id="portfolioToggle" style="display:none;">
#include('entidades.portfolio')
</div>
<!-- /////////////////////////////////////////////////////////////////////// -->
<!-- /////////////////////////////////Parecer/////////////////////////////// -->
<!-- /////////////////////////////////////////////////////////////////////// -->
<div id="parecerToggle" style="display:none;">
#include('entidades.parecer')
</div>
<!-- botão para gerar súmula -->
<button class="btn btn-primary" type="submit" id="gerarBtn" action="pagina.php" >
Gerar Súmula
</button>
</form>
<div class="ajax-loader" style = "display:none;">
<img src="{{ url('img/ajax-loader.gif') }}" class="img-responsive" />
</div>
</div>
#endsection
Controler:
public function store(Request $request){
......
return json_encode(['limFinal'=> $limFinal, 'mci'=> $mci, 'risco1'=>$risco1, 'risco2'=>$risco2,
'auxCheqOuro'=>$auxCheqOuro, 'auxCartaoEmp'=>$auxCartaoEmp]);
}
Related
I have select option (dropdown list) inside a modal in which the option are getting printed below the dropdownlist... I tried checking if the code works if i redirect the page and works, like the options are inside the dropdown box but same thing inside modal doesn't work? Any solutions would be helpful.
add_details.blade
<div class="container">
<div class="row">
<div class="col">
<div>
<h2>Enter Your Details</h2>
<form action="{{ route('save') }}" method="POST" enctype="multipart/form-data">
#csrf
<div>
<div>
<span style="color:black">
<select class="form-control" name="collegeID" id="college_name" required />
<option value="" disabled selected hidden>Select College</option>
#foreach ($college_names as $college_name)
<option value="{{$college_name->collegeID}}">
{{ $college_name->college_name }}
</option>
#endforeach
</select>
</span>
</div>
</div>
<br />
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<input type="radio" value="Cbse" name="regno">
<label for="" style="color:black">CBSE</label>
<input type="radio" value="State" name="regno"> <label style="color:black">PUC</label>
<input type="radio" value="State" name="regno"> <label style="color:black">State</label>
<div id="showCbse" class="myDiv">
<label for="regno" class="form-label"><span style="color:black">Admission Number</span></label>
<input type="number" name="regno" class="form-control" placeholder="Enter valid Admission Number" />
#if ($errors->has('regno'))
<span class="text-danger">{{ $errors->first('regno') }}</span>
#endif
</div>
<div id="showState" class="myDiv">
<label for="regno" class="form-label"><span style="color:black">Register Number</span></label>
<input type="number" name="regno" class="form-control" placeholder="Enter valid Register Number" />
#if ($errors->has('regno'))
<span class="text-danger">{{ $errors->first('regno') }}</span>
#endif
</div>
</div>
</div>
</br>
<label for="name" class="form-label"><span style="color:black">Name</span></label>
<input type="text" name="name" class="form-control" value="{{old('name')}}" placeholder="Enter Name" required />
#if ($errors->has('name'))
<span class="help-block font-red-mint">
<strong>{{ $errors->first('name') }}</strong>
</span>
#endif
</div>
<div>
</br>
<label for="address" class="form-label"><span style="color:black">Address</span></label>
<input type="text" name="address" value="{{old('address')}}" class="form-control" placeholder="Enter Address" required />
#if ($errors->has('address'))
<span class="help-block font-red-mint">
<strong>{{ $errors->first('address') }}</strong>
</span>
#endif
</div>
<div>
</br>
<label for="yop" class="form-label"><span style="color:black">Year Of Passing</span></label>
<input type="date" name="yop" value="{{old('yop')}}" class="form-control" placeholder="Enter Year Of Passing" required />
#if ($errors->has('yop'))
<span class="help-block font-red-mint">
<strong>{{ $errors->first('yop') }}</strong>
</span>
#endif
</div>
<div>
</br>
<label for="email" class="form-label"><span style="color:black">Email</span></label>
<input type="email" name="email" value="{{old('email')}}" class="form-control" placeholder="Enter Email" required />
#if ($errors->has('email'))
<span class="help-block font-red-mint">
<strong>{{ $errors->first('email') }}</strong>
</span>
#endif
</div>
<div>
</br>
<label for="phone" class="form-label"><span style="color:black">Phone Number</span></label>
<input type="number" name="phone" value="{{old('phone')}}" class="form-control" placeholder="Enter Phone Number" required />
#if ($errors->has('phone'))
<span class="help-block font-red-mint">
<strong>{{ $errors->first('phone') }}</strong>
</span>
#endif
</div>
<br /> <br />
<div class="col-md-4">
</br>
<button type="submit" class="btn btn-primary">Add</button>
</form>
<button type="submit" class="btn btn-primary">Back</button>
</div>
</div>
<style>
.myDiv {
display: none;
padding: 10px;
}
</style>
<script>
$(document).ready(function() {
$('input[type="radio"]').click(function() {
var demovalue = $(this).val();
$("div.myDiv").hide();
$("#show" + demovalue).show();
});
});
</script>
add.blade (page where the modal pops up)
<link href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.min.css" rel="stylesheet">
<link href="https://cdn.datatables.net/1.10.19/css/dataTables.bootstrap4.min.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap4.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.20/b-1.6.1/b-flash-1.6.1/b-html5-1.6.1/b-print-1.6.1/r-2.2.3/datatables.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.1/umd/popper.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.6.0/js/bootstrap.min.js"></script>
<!-- Font Awesome -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/js/all.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<!-- Datepicker -->
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link href="css/bootstrap-select.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="js/bootstrap-select.min.js"></script>
#extends('auth.dashboard')
#section('title')
Dashboard
#endsection
#section('body')
#if(Session::has('success'))
<div class="alert alert-success alert-dismissible">
{{Session::get('success')}}
</div>
#elseif(Session::has('failed'))
<div class="alert alert-success alert-dismissible">
{{Session::get('failed')}}
</div>
#endif
<body>
</br>
<div class="container">
<div class="row">
<div class="col">
<div>
<div class="pull-right">
<a class="btn btn-primary" title="Add"
href="{{route('add_details')}}"><i class="fas fa-plus-circle"></i></a>
<a class="btn btn-sm" data-toggle="modal" id="mediumButton" data-target="#mediumModal" data-attr="{{ route('add_details')}}" title="Add Institute Details"> ADD
</a>
</div>
</br>
</br>
</br>
<div class="row">
<div class="col-12 table-responsive">
<table class="table table-striped table-bordered user_datatable" id="user_datatable">
<thead class="thead-dark div-2">
<tr>
<center> <th><strong><span style="color:white">ID</span></strong></th> </center>
<th><strong><span style="color:white">Name</span></strong></th>
<th><span style="color:white">Status</span></th>
<th width="15%"><span style="color:white">Action</span></th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
<!-- medium modal -->
<div class="modal fade" id="mediumModal" tabindex="-1" role="dialog" aria-labelledby="mediumModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body" id="mediumBody">
<div>
<!-- the result to be displayed apply here -->
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript" src="https://cdn.datatables.net/v/bs4/jszip-2.5.0/dt-1.10.20/b-1.6.1/b-flash-1.6.1/b-html5-1.6.1/b-print-1.6.1/r-2.2.3/datatables.min.js">
</script>
<script type="text/javascript" src="https://cdn.datatables.net/responsive/2.2.7/js/dataTables.responsive.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$.noConflict();
fill_datatable();
function fill_datatable(collegeID = '') {
var table = $('.user_datatable').DataTable({
order: [
[0, 'desc']
],
processing: true,
serverSide: true,
ajax: {
url: "{{ route('alumni.datatable') }}",
data: {
collegeID: collegeID
}
},
columns: [{
data: 'id',
name: 'id'
},
{
data: 'name',
name: 'name'
},
{
data: 'status',
name: 'status',
mRender: function(data) {
if (data == '1') {
return '<center><span class = "btn btn-danger btn-sm" > Pending </span></center>'
}
if (data == '0') {
return '<center><span class = "btn btn-success btn-sm" > Approved </span></center>'
}
}
},
{
data: 'action',
name: 'action',
orderable: false,
searchable: false
},
]
});
}
$('#filter').click(function() {
var collegeID = $('#college_name').val();
if (collegeID != '') {
$('#user_datatable').DataTable().destroy();
fill_datatable(collegeID);
} else {
alert('Select Both filter option');
}
});
});
</script>
<script>
// display a modal (medium modal)
$(document).on('click', '#mediumButton', function(event) {
event.preventDefault();
let href = $(this).attr('data-attr');
$.ajax({
url: href,
beforeSend: function() {
$('#loader').show();
},
// return the result
success: function(result) {
$('#mediumModal').modal("show");
$('#mediumBody').html(result).show();
},
complete: function() {
$('#loader').hide();
},
error: function(jqXHR, testStatus, error) {
console.log(error);
alert("Page " + href + " cannot open. Error:" + error);
$('#loader').hide();
},
timeout: 8000
})
});
</script>
#endsection
It's minor mistake all devs do :D , I also did this type of mistake.
use
<select class="form-control" name="collegeID" id="college_name" required>
Instead of this
<select class="form-control" name="collegeID" id="college_name" required />
Just remove close tag from end of the start tag.
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();
}
});})
I'm trying to fill a table in a jsp with a List I put in the model from a Spring controller but the table is not being filled. This is the page:
<%# page import="cl.onvision.dte.be.utils.*" %>
<%
String order = request.getParameter("o");
String search = request.getParameter("s");
String strTitulo = "Gestor usuarios";
%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
<meta http-equiv="Pragma" content="no-cache" />
<meta http-equiv="Expires" content="0" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<title>Administrador / Inicio</title>
</head>
<body>
<!-- Header layer -->
<div class="container">
<div class="row" style="background-color: rgb(255,130,0); padding: 10px">
<div class="col-sm-3"><img src="/img/index/slogan150.png" /></div>
<div class="col-sm-4"></div>
<div class="col-sm-5 text-right text-white">
<!--a href="/login/salir">Salir</a-->
<%#include file="/views/include/bannerSesion.jsp"%>
</div>
</div>
</div>
<!-- Menu layer -->
<div class="container">
<ul class="nav nav-tabs nav-justified">
<li class="nav-item"><a class="nav-link" href="/admin/inicio">Inicio</a></li>
<li class="nav-item"><a class="nav-link" href="/admin/usuarios">Gestion Usuarios</a></li>
<li class="nav-item"><a class="nav-link" href="/admin/contrib">Gestion Contribuyentes</a></li>
<li class="nav-item"><a class="nav-link" href="/admin/alertas">Alertas</a></li>
<li class="nav-item"><a class="nav-link active" href="/admin/ciudades">Ciudades</a></li>
</ul>
</div>
<br />
<!-- Search & button upper-layer -->
<div class="container">
<div class="row">
<div class="col-sm-6">
<b>Búsqueda:</b>
<input type="text" class="input-sm" style="height:25px" id="s" value="<%= (search==null)? "": search %>"
maxlength="20" size="20" autofocus />
<input type="hidden" id="o" value="<%= (order==null)? "": order %>" />
</div>
<div class="col-sm-6 text-right">
<button data-toggle="modal" data-target="#modaladd" class="btn btn-sm btn-success">
<i class="material-icons" style="font-size:22px">person_add</i>
</button>
</div>
</div>
</div>
<div style="height:10px"></div>
<!-- Data list -->
<div class="container">
<div class="table-responsive">
<table class="table table-striped table-hover table-bordered table-condensed table-sm">
<thead>
<tr>
<th style="text-align:center">#</th>
<th style="text-align:center">Nombre usuario</th>
<th style="text-align:center">Region</th>
<th style="text-align:center">Acciones</th>
</tr>
</thead>
<tbody>
<c:forEach var="ciudad" items="${ciudades}">
<tr>
<td style="text-align:center"><c:out value="${ciudad.id}"/></td>
<td style="text-align:center"><c:out value="${ciudad.nombre}"/></td>
<td style="text-align:center"><c:out value="${ciudad.region}"/></td>
<td class="pl-5">
<a href="/admin/usuario/eliminar/${ciudad.id}/">
<button class="btn btn-sm btn-primary"><i class="material-icons"
style="font-size:16px">remove_circle</i></button>
</a>
<a href="javascript:leerDatos(${ciudad.id});">
<button class="btn btn-sm btn-warning"><i class="material-icons"
style="font-size:16px">border_color</i></button>
</a>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</div>
<a href="#" id="axls" style="display:none;" donwload>a</a>
<!-- Modal 'add user' form-->
<div class="modal" id="modaladd">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header bg-info text-white">
<h2 class="modal-title">Agregar nuevo usuario</h2>
</div>
<!-- Modal body -->
<form method="post" action="/admin/usuario/agregar">
<div class="modal-body">
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="nom">Nombre de usuario:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="nomusu" id="nom" maxlength="40"
required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="run">RUN:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="runusu" id="run" maxlength="40"
required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="cla">Nueva clave:</label></div>
<div class="col-sm-8">
<input type="password" class="form-control input-sm" name="cla1usu" id="cla"
maxlength="20" required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="cla2">Repita la clave:</label></div>
<div class="col-sm-8">
<input type="password" class="form-control input-sm" name="cla2usu" id="cla2"
maxlength="20" required />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="com">Comentarios:</label></div>
<div class="col-sm-8">
<textarea class="form-control input-sm" name="comentusu" id="com" rows="3"
cols="80"></textarea>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Agregar nuevo usuario" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
<!-- Modal 'update user' form-->
<div class="modal" id="modalupdate">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header bg-info text-white">
<h2 class="modal-title">Modificar usuario</h2>
</div>
<!-- Modal body -->
<form method="post" action="/admin/usuario/modificar">
<div class="modal-body">
<input type="hidden" name="uid" id="uid" value="" />
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="unom">Nombre de usuario:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="unomusu" id="unom" maxlength="40"
readonly />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="urun">RUN:</label></div>
<div class="col-sm-8">
<input type="text" class="form-control input-sm" name="urunusu" id="urun" maxlength="40"
readonly />
</div>
</div>
<div class="row" style="margin-bottom:10px">
<div class="col-sm-4"><label for="ucom">Comentarios:</label></div>
<div class="col-sm-8">
<textarea class="form-control input-sm" name="ucomentusu" id="ucom" rows="3"
cols="80"></textarea>
</div>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<input type="submit" class="btn btn-success" value="Modificar datos" />
<button type="button" class="btn btn-danger" data-dismiss="modal">Cancelar</button>
</div>
</form>
</div>
</div>
</div>
</body>
<script>
function ordenarDatos(campo) {
url = 'gestionUsuarios.jsp?o=' + campo + '&s=' + $('#s').val();
document.location.href = url;
return null;
}
/*function descargarXls()
{
url1 = '${pageContext.request.contextPath}/ExtraerXlsUsuarios.do';
$.ajax( {url: url1,
success: function(result)
{
//$('#axls').attr('href', "../" + result);
location.href = "../" + result; //$('#axls').attr('href');
} });
}*/
$('#s').keypress(function (event) {
if (event.which == 13) {
document.location.href = 'gestionUsuarios.jsp?o=' + $('#o').val() + '&s=' + $('#s').val();
return null;
}
}
);
function leerDatos(id) {
$.post("/admin/usuario/ver/" + id + "/", function (obj) {
obj = JSON.parse(obj);
$('#uid').val(obj.id);
$('#unom').val(obj.nom);
$('#urun').val(obj.run);
$('#ucom').val(obj.com);
$('#modalupdate').modal('show');
obj = null;
});
}
/*$().ready( function()
{
v = $('#s').val();
$('#s').val('');
$('#s').val(v);
});*/
</script>
</html>
I'm putting the list into the model right, as you can see in the chrome developer tools:
I can't see the problem here, I need help trying to figure out why the table is not being filled.
Try including the <%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> athe top of your code. Also, make sure your object name ciudades is spelled as it is in your controller.
Well my problem was thwo things:
I'm using tomcat as webapp which doesn't bring JSTL embeddeb. So I had to add the dependency in the pom.xml.The version is important if you want to use EL's.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I had to add the taglib on top of the JSP to access the <c:> tags. Thanks to #Morteza Bandi for the heads up.
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
I am using laravel 7 and default auth with ajax login & registration and bootstrap 4 modal window. But after login resend verification link and while registration shows "CSRF token Mismatch error", here is my code below:
#ajax setup#
$(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
});
//login with ajax
$(function(){
$("#loginForm").on("submit", function(e){
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var type = form.attr("method");
var data = new FormData(form[0]);
//console.log(data.response);
$.ajax({
url: url,
data: data,
type: type,
processData:false,
contentType: false,
success:function(){
//reset form data
$( '#loginForm' ).each(function(){
this.reset();
});
$('#login').modal('hide');
$(".top_header_area").load('/'+ ' .top_header_area');
//success message
toastr.success('Login Successfull <i class="fas fa-smile"></i>','Success',{
closeButton: true,
progressBar: true
});
},
error:function(xhr,status,error){
//console.log(xhr.status);
//console.log(xhr.responseJSON.message);
if(xhr.status === 403){
$('#login').modal('hide');
//reload header panel
$(".top_header_area").load('/'+ ' .top_header_area');
$('#verify').modal('show');
toastr.error(xhr.responseJSON.message,'Error',{
closeButton: true,
progressBar: true
});
}
errors = xhr.responseJSON.errors;
$.each(errors, function(key, value){
//shows error message
toastr.error(value,'Error',{
closeButton: true,
progressBar: true
});
});
},
});
});
});
//Register with ajax
$(function(){
$("#registerForm").on("submit", function(e){
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var type = form.attr("method");
var data = new FormData(form[0]);
//console.log(data.response);
$.ajax({
url: url,
data: data,
type: type,
processData:false,
contentType: false,
success:function(){
//reset form data
$( '#registerForm' ).each(function(){
this.reset();
});
$('#register').modal('hide');
//success message
toastr.success('Registration Successfull <i class="fas fa-smile"></i>','Success',{
closeButton: true,
progressBar: true
});
},
error:function(xhr,status,error){
if(xhr.status === 403){
$('#register').modal('hide');
//reload header panel
$(".top_header_area").load('/'+ ' .top_header_area');
$('#verify').modal('show');
toastr.error(xhr.responseJSON.message,'Error',{
closeButton: true,
progressBar: true
});
}
errors = xhr.responseJSON.errors;
$.each(errors, function(key, value){
//shows error message
toastr.error(value,'Error',{
closeButton: true,
progressBar: true
});
});
},
});
});
});
//request verification email
$(function(){
$("#resendLink").on("submit", function(e){
e.preventDefault();
var form = $(this);
var url = form.attr("action");
var type = form.attr("method");
var data = new FormData(form[0]);
$.ajax({
url: url,
type: type,
data: data,
processData:false,
contentType: false,
success:function(){
$(".top_header_area").load('/'+ ' .top_header_area');
//reset form data
$( '#resendLink' ).each(function(){
this.reset();
});
$('#verify').modal('hide');
//success message
toastr.success('Verification Link Send <i class="fas fa-smile"></i>','Success',{
closeButton: true,
progressBar: true
});
},
});
});
});
when I check the network tab in the browser Request Cookie and Response Cookie value is different and I am using login, registration, resend verification link all forms are in modals in the same app.blade.php blade layout.
after login when click on "resend verification link" button form it shows "csrf token mismatch" but after refresh the page it works!
I am sending 2 ajax request from the same page....
1. login
2. resend verification link
but registration form sending 1 ajax request but again showing same error.
forms are below:
<!-- Modal -->
<div class="modal fade" id="login" tabindex="-1" role="dialog" aria-labelledby="loginTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content wow fadeInUp" data-wow-delay=".3s">
<div class="modal-header">
<h5 class="modal-title" id="loginTitle"><i class="fas fa-sign-in-alt"></i> LOGIN</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body contact-form">
<form id="loginForm" action="{{ route('login') }}" method="post">
#csrf
<div class="form-group">
<input id="loginEmail" type="email" placeholder="Email Address" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" autocomplete="email" autofocus>
</div>
<div class="form-group">
<input id="LoginPassword" placeholder="Password" type="password" class="form-control #error('password') is-invalid #enderror" name="password" autocomplete="current-password">
</div>
<div class="form-group">
<div class="custom-control custom-checkbox">
<input class="custom-control-input" type="checkbox" name="remember" id="remember" {{ old('remember') ? 'checked' : '' }}>
<label class="custom-control-label" for="remember">
{{ __('Remember Me') }}
</label>
</div>
</div>
<button class="btn btn-lg btn-block text-uppercase button" type="submit">{{ __('Login') }}</button>
<hr>
#if (Route::has('password.request'))
<a class="btn btn-link link" href="#" data-dismiss="modal" data-toggle="modal" data-target="#reset">
{{ __('Forgot Your Password?') }}
</a>
#endif
<hr class="my-4">
<p>Don't have account? Register</p>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- ****** Register modal Start ****** -->
<!-- Modal -->
<div class="modal fade" id="register" tabindex="-1" role="dialog" aria-labelledby="registerTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content wow fadeInUp" data-wow-delay=".3s">
<div class="modal-header">
<h5 class="modal-title" id="registerTitle"><i class="fas fa-user-plus"></i> REGISTER</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body contact-form">
<form id="registerForm" action="{{ route('register') }}" method="post">
#csrf
<div class="form-group">
<input id="name" type="text" placeholder="Name" class="form-control #error('name') is-invalid #enderror" name="name" value="{{ old('name') }}" autocomplete="name" autofocus>
</div>
<div class="form-group">
<input id="username" type="text" placeholder="Username" class="form-control #error('username') is-invalid #enderror" name="username" value="{{ old('username') }}" autocomplete="username" autofocus>
</div>
<div class="form-group">
<input id="registerEmail" type="text" placeholder="E-mail" class="form-control #error('email') is-invalid #enderror" name="email" value="{{ old('email') }}" autocomplete="email" autofocus>
</div>
<div class="form-group">
<input id="registerPassword" type="password" placeholder="Password" class="form-control #error('password') is-invalid #enderror" name="password" autocomplete="new-password">
</div>
<div class="form-group">
<input id="register-password-confirm" type="password" placeholder="Confirm Password" class="form-control" name="password_confirmation" autocomplete="new-password">
</div>
<button class="btn btn-lg btn-block text-uppercase button" type="submit">{{ __('Register') }}</button>
<hr class="my-4">
<p>Already REGISTERED LOGIN</p>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- ****** Verify modal Start ****** -->
<!-- Modal -->
<div class="modal fade" id="verify" tabindex="-1" role="dialog" aria-labelledby="verifyTitle" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content wow fadeInUp" data-wow-delay=".3s">
<div class="modal-header">
<h5 class="modal-title" id="verifyTitle"><i class="fas fa-certificate heading"></i> {{ __('Verify Your Email Address') }}</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
#if (session('resent'))
<div class="alert alert-success" role="alert">
{{ __('A fresh verification link has been sent to your email address.') }}
</div>
#endif
{{ __('Before proceeding, please check your email for a verification link.') }}
{{ __('If you did not receive the email') }},
<!-- {{ __('click here to request another') }} -->
<form id="resendLink" class="d-inline" method="POST" action="{{ route('verification.resend') }}">
#csrf
<button type="submit" class="btn btn-link p-0 m-0 align-baseline">{{ __('click here to request another') }}</button>.
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn button" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
To solve this problem you have to add "X-CSRF-TOKEN" to main layout <head></head> tag. The VerifyCsrfToken middleware will also check for the X-CSRF-TOKEN request header. You could store the token in an HTML meta tag:
<meta name="csrf-token" content="{{ csrf_token() }}">
Then, once you have created the meta tag, you can instruct a library like jQuery to automatically add the token to all request headers. This provides simple, convenient CSRF protection for your AJAX based applications:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
For More details please visit CSRF Protection Laravel-docs 7.x
the following is the modal which is invoked on button click
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Compose New Task</h4>
</div>
<div class="modal-body db">
<div class="form-group db">
<label class="col-sm-6 control-label">Current Password </label>
<div class="col-sm-6">
<input type="password" id="current_password" class="form-control">
</div>
</div>
<div class="form-group">
<label class="col-sm-6 control-label">New Password </label>
<div class="col-sm-6">
<input type="password" id="new_password" class="form-control">
<input type="hidden" value="{{ csrf_token() }}" id="csrftoken">
</div>
</div>
<div class="form-group">
<div class="error" id="message"></div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="updatePassword">Save changes</button>
</div>
</div>
</div>
Relevant line in the above code is number 11
$("#updatePassword").click(function () {
var current_password = document.getElementById('current_password').value;
var new_password = document.getElementById('new_password').value;
var token = document.getElementById('csrftoken').value;
$.post('/modalupdatePassword', {'current_password': current_password, 'new_password': new_password, '_token': token}, function (data) {
var parsed = JSON.parse(data);
console.log(parsed);
$('#message').append(parsed);
});
});
and this is my modalPasswordUpdate function
public function modalUpdate(Request $request)
{
$current_password = bcrypt($request->current_password);
$updateRequest = User::where('id', Auth::user()->id)
->where('password', $current_password)
->first();
echo json_encode($current_password);
}
Now every time I send the request I am getting different hash
following is my updated code
Route::get('check', function()
{
echo $password = Hash::make('secret');
});
this also returns new password everytime
You are sending your request via post. Laravel documentation states, that the VerifyCsrfToken middleware will look for X-CSRF-TOKEN request headers during post requests, so do try the following.
Add the token to a meta tag in the head of your document.
<meta name="csrf-token" content="{{ csrf_token() }}" />
Now add the X-CSRF-TOKEN as a header to the global ajax settings like so
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Now all AJAX requests will automatically include the CSRF token.
You can read more about this on the Laravel docs right here.