Frontend validation on Fortify Login in Laravel with AJAX - ajax

I'm using Fortify to manage users authentication and I have a modal form for the login. My problem is every time I submit the form I can't see any errors because the page refreshes and closes the modal with the login form.
I would like to know if this validation is possible in the frontend without refreshing the page so the modal won't close. I've tried with Ajax but I can't find the right way to manage this or even in which controller I'm supposed to handle the if statement for the response.
I'll be really thankful if anyone could help me.
Here's my modal:
<!-- LOGIN Modal -->
<form action="{{ route('login') }}" method="post">
#csrf
<div class="modal fade" id="login" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" >
<div class="modal-content">
<div class="modal-header">
<h5>Login</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<div class="alert alert-danger print-error-msg" style="display:none">
<ul></ul>
</div>
<div class="mb-3 row">
<div class="col-sm"><br>
<input type="text" class="form-control" name="email" value="Email">
</div>
</div>
<div class="mb-3 row">
<div class="col-sm">
<input type="password" class="form-control" id="inputPassword" name="password" value="Password">
</div>
</div>
<div class="d-grid gap-2">
<button type="submit" id="btn-login" class="btn btn-login">Continuar</button>
</div>
</div>
<div class="modal-footer">
<label><u>Recuperar password</u></label>
</div>
</div>
</div>
</div>
</form>
And here's the Ajax:
$(document).ready(function() {
$("#btn-login").click(function(e) {
e.preventDefault();
var _token = $("input[name='_token']").val();
var email = $("input[name='email']").val();
var password = $("input[name='password']").val();
$.ajax({
url: config.routes.zone,
type: 'POST',
data: { _token: _token, email: email, password:password },
success: function(data) {
if ($.isEmptyObject(data.error)) {
window.location.href = {{ route('login') }};
} else {
printErrorMsg(data.error);
}
}
});
});
function printErrorMsg(msg) {
$(".print-error-msg").find("ul").html('');
$(".print-error-msg").css('display', 'block');
$.each(msg, function(key, value) {
$(".print-error-msg").find("ul").append('<li>' + value + '</li>');
});
}
});

Related

Page expired when submitting form

I am using a modal, and when opens the modal then close it, then open it again to add user, it says page expired upon submitting.
here is the my modal with my form
<div class="modal fade" wire:ignore.self id="studentModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog modal-xl">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Patient Registration</h5>
#if(Session::has('message'))
<p class="alert {{ Session::get('alert-class', 'alert-info') }}">{{
Session::get('message') }}</p>
#endif
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" id="closeReset1" onclick="resetInput()"></button>
</div>
<!-- START FORM -->
<form action="add" method="POST">
#csrf
<!-- START MODAL BODY -->
<div class="modal-body">
</div>
<div class="modal-footer"
</div>
</form>
</div>
</div>
here is my route
Route::post('/add', [App\Http\Livewire\UHispatients::class, 'savePatient'])->name('registerPatient');
if you are using the naming route and check your model fillable
<form action="{{route('registerPatient')}}" method="POST">
#csrf
<!-- START MODAL BODY -->
<div class="modal-body">
</div>
<div class="modal-footer"
</div>
<button type="submit">submit</button>
</form>
As I can see, you just forgot to put action for your form in your modal.
If you submit using the submit button, then your problem is using the route path "add" instead of using the route path or route name.So as your route has name you can use it like this :
<form action="{{route('registerPatient')}}" method="POST">
#csrf
<!-- START MODAL BODY -->
<div class="modal-body">
</div>
<div class="modal-footer"
</div>
<button type="submit">submit</button>
</form>
If you're submitting your form with Ajax, then the csrf tag should be sending with your Ajax request. So, your Ajax header should be like this :
<script type="text/javascript">
$('#YOUR_FORM_ID').on('submit',function(e){
e.preventDefault();
let name = $('#name').val();
$.ajax({
url: "{{route('registerPatient')}}",
type:"POST",
data:{
"_token": "{{ csrf_token() }}",
name:name,
},
success:function(response){
console.log(response);
},
error: function(response) {
console.log(response);
}
});
});
</script>

Delete form data after data is displayed or submission of the form

I use the same form to view details of a record that is in the database and make form submission. But an error occurs when I view a log and then register other data. In this case the new registration is registered three times in the database. And the reason this happens is that the form data is cached when I view or register a record. All the solutions I searched on the internet didn't work for me.
This is my form
<div id="form" style="display: none;" class="col-md-12">
<div class="row">
<h5 class="title">Add</h5>
<div class="float-right" style="margin-left: 80%">
<button class="btn btn-secondary" id="close_form">Close</button>
</div>
</div>
<form method="post" id="sample_form" class="form-horizontal" enctype="multipart/form-data">
#csrf
<div class="row">
<div class="col-md-12">
<div class="card card-primary">
<div class="card-header">
<div class="card-tools">
<button type="button" class="btn btn-tool" data-card-widget="collapse" data-toggle="tooltip" title="Collapse">
<i class="fas fa-minus"></i></button>
</div>
</div>
<div class="card-body">
<fieldset disabled>
<div class="row">
<div class="form-group col-md-3">
<label for="inputCity">Código do documento:</label>
<input type="text" class="form-control" id="id_docs" name="id_docs">
</div>
<div class="form-group col-md-8">
<label for="inputCity">Status</label>
<input type="text" class="form-control" id="status" name="status">
</div>
</div>
</fieldset>
<div class="form-group">
<label>Assunto</label>
<textarea class="form-control" id="assunto" name="assunto" required></textarea>
</div>
<div class="form-group">
<label for="inputAddress2">Proveniencia</label>
<input type="text" class="form-control" id="prov" placeholder="Proveniencia" name="prov" required>
</div>
<div class="form-group col-md-4">
<label for="inputCity">Correspondência</label>
<input type="date" class="form-control" id="corre" name="corre">
</div>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12" id="img_cad" style="margin-left: 10px;">
<span class="control-label col-md-4"><b class="span_doc">File:</b></span><br><br>
<input type="file" id="image" aria-describedby="inputGroupFileAddon01" name="image">
<span id="store_image"></span>
</div><br>
<br>
<input type="hidden" name="action" id="action" />
<input type="hidden" name="hidden_id" id="hidden_id" />
<input type="hidden" name="hidden_id_docs" id="hidden_id_docs" />
<button type="submit" name="action_button" id="action_button" class="btn btn-warning">Save</button>
</div>
</div>
</form>
</div>
This is the function to view the details of a record on the form
$(document).on('click', '.edit', function(){
var id_scr = $(this).attr('id_scr');
$('#div_table').hide();
$.ajax({
url:"/scr/"+id_scr+"/edit",
cache: false,
dataType:"json",
success:function(html){
$('#action_button').text("Edit Data");
$('#assunto').val(html.data.assunto);
$('#prov').val(html.data.prov);
$('#corre').val(html.data.corre);
$('#status').val(html.data.descricao);
$('#cod_cadastro').val(html.data.cod_cadastro);
$('#hidden_id').val(html.data.id);
$('#hidden_id_docs').val(html.data.id_docs);
$('#id_docs').val(html.data.id_docs);
$('.title').text("Details...");
$('.span_doc').text("Alter Doc");
$('#action').val("Edit");
$('#form').show();
}
})
});
To clear the form data after viewing a record, I created thisTo clear the form data after viewing a record, I created this function:
$(document).on('click', '#close_form', function(){
$('#sample_form')[0].reset();
$('#form').hide();
$('#div_table').show();
});
And finally, this is the function for registering a new record
$('#sample_form').on('submit', function(event){
event.preventDefault();
$('.progress').show();
if($('#action').val() == 'Add')
{
$.ajax({
url:"{{ route('scr.store') }}",
method:"POST",
data: new FormData(this),
contentType: false,
cache:false,
processData: false,
dataType:"json",
success:function(data)
{
alert('SUCCESSFULLY SAVED');
$('#sample_form')[0].reset();
$('#formModal').modal('hide');
location.reload(); //**This is the only way I found to clear the form after submitting the data**
}
})
}
})
You could try this method :
function submitForm() {
// Get the first form with the name
// Usually the form name is not repeated
// but duplicate names are possible in HTML
// Therefore to work around the issue, enforce the correct index
var frm = document.getElementsByName('contact-form')[0];
frm.submit(); // Submit the form
frm.reset(); // Reset all form data
return false; // Prevent page refresh
}
Or you could just call this method in your submit method

Bootstrap 4 destroy a modal when it is closed

I'm looking for a solution on my problem. I'm using bootstrap4 on laravel project. I have a modal that has a button which close it self and open a new modal. This is the code:
$("#newAddressBtn").on('click', function () {
$('#modalAddressees').modal('hide')
$('#modalAddressees').on('hidden.bs.modal', function () {
// Load up a new modal...
$('#modalNewAddress').modal('show');
})
});
Inside this new modal (modalNewAddress) I have a button that dismiss it. But when I dismiss it, I would to destroy it self because if I need to re-open it again, I would to start with empty data inside (such us the first show).
I wrote this code but nothing happens:
[....]
.on('core.form.valid', function () {
$.ajax({
url: "{{ route("addresses.store") }}",
headers: {'X-CSRF-Token': $('meta[name=_token]').attr('content')},
dataType: "JSON",
data: $("#addressForm").serialize(),
type: "POST",
success: function (data) {
destroyModal("#modalNewAddress");
},
error: function (data) {
console.log('error ' + data);
}
});
});
[....]
function destroyModal(modal){
$(modal).modal('dispose');
}
This is the code of the modal:
<div class="modal fade" tabindex="-1" role="dialog" id="modalNewAddress">
<div class="modal-dialog modal-lg" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">New Address</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form method="POST" id="addressForm" action="{{ route("addresses.store") }}" class="needs-validation" novalidate="">
{{ csrf_field() }}
<div class="form-group row">
<label for="name" class="col-sm-3 col-form-label">Name</label>
<div class="col-sm-9">
<input type="text" class="form-control" name="name" id="name" value="" placeholder="Name" required="">
</div>
</div>
<span class="float-right">
<button type="submit" id="save" class="btn btn-primary">Save</button>
</span>
<input type="hidden" name="ajax">
</form>
</div>
<div class="modal-footer bg-whitesmoke br">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
How can I solve the problem? Could you please help me?
You're not supposed to destroy the modal but recycle it.
The usage pattern would be as follows:
the modal does not contain data, but data fields you can reach with jQuery, such as:
<div id="adress-nome"></div>
<!-- more fields ... -->
before you open the modal, you populate it with a function, such as:
function updateModal(data)
{
$("#address-nome").val(data.nome);
// more data ...
}
function openModal(data)
{
updateModal(data);
$("#address-modal").modal("show");
}
when you're done with the modal, just hide it
when you re-open it, it will contain the new data

laravel 7 csrf token mismatch

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

how to work with laravel modal using ajax

Iam working on a simple laravel project where i have a page with http://loocalhost:8000/home as url .i have a button on the page.clicking the button will open a modal where i will have a form.What my problem is whenever i submit the form in the modal the data should be saved in database .i want to implement it by using ajax and then pass it to controller.but i don't know how to implement it exactly.
my modal in
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<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>
<h4 class="modal-title" id="myModalLabel">New post</h4>
</div>
<div class="modal-body">
<form id="frmPost" name="frmPost" class="form-horizontal" novalidate="">
<div class="form-group error">
<label for="inputName" class="col-sm-3 control-label">Title</label>
<div class="col-sm-9">
<input type="text" class="form-control has-error" id="title" name="title" placeholder="Title" value="">
</div>
</div>
<div class="form-group">
<label for="inputDetail" class="col-sm-3 control-label">Description</label>
<div class="col-sm-9">
<input type="text" class="form-control" id="description" name="description" placeholder="Description" value="">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" id="btn-save" value="">Add</button>
<!-- <input type="hidden" id="product_id" name="product_id" value="0"> -->
</div>
</div>
</div>
my home page with url :http://localhost:8000/home
<button id="btn_add" name="btn_add" class="btn btn-default">New Post</button>
my ajax code :
$('#btn_add').click(function(){
var url = "http://localhost:8080/home";
$('#btn-save').val("add");
$('#frmPost').trigger("reset");
$('#myModal').modal('show');
$('#btn-save').click(function(e){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf_token()"]').attr('content')
}
})
var formData = {
'title':$('#title').val(),
'description' :$('#description').val()
}
$.ajax({ //line 28
url: url,
type: 'POST',
data: { userData: formData },
success: function()
{
alert("Settings has been updated successfully.");
}
});
});
});
routes.php code:
Route::get('/home', 'HomeController#index');//route for home page after login
Route::post('/home', 'HomeController#addPost');//route to go after submitting modal data.
But i am getting error i dont know what the issue.can someone help me?
My error:
jquery.js?27d9:9536 POST http://localhost:8080/home net::ERR_CONNECTION_REFUSED

Resources