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
Related
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>');
});
}
});
User have to register through two steps. both steps have modal to fill details. for that i have two component ComponentA for first modal and componentB for second modal. Iwant to close first modal on axios success response and open second modal for second registration step.
<template>
<!--sction user-signup 1-->
<div class="signup">
<div class="modal" id="user-signup-1">
<div class="modal-dialog">
<div class="modal-content">
<button type="button" class="close" data-dismiss="modal">×</button>
<!-- Modal body -->
<div class="modal-body text-center" style="background:url(images/user-signup-bg.jpg) no-repeat left top; ">
<h2>SIGN UP</h2>
<h5 class="setp-tag">Step 1 of 2</h5>
<h6>Registered users have access to all MoneyBoy features. This is not a Moneyboy Profile.<br>
If you’d like to create a Moneyboy Profile please click here.</h6>
<form class="user-signup-form" action="./api/user/signup" method="POSt" #submit.prevent="addUser()">
<div class="form-group">
<label>Username</label>
<input type="text" name="username" v-model="username" placeholder="mohamed-ali" class="span3 form-control">
<span v-if="hidespan">5 - 20 characters. Letters A-Z and numbers 0-9 only. No spaces.
E.g. MikeMuscleNYC.</span>
<span v-if="errorinusername"> {{ errorinusername }}</span>
</div>
<div class="form-group">
<label>Email</label>
<input type="email" name="email" v-model="email" placeholder="mohamed-ali#gmail.com" class="span3 form-control">
<span v-if="errorinemail"> {{ errorinemail }}</span>
</div>
<div class="form-group">
<label>Create a password</label>
<input type="password" name="password" v-model="password" placeholder="**********" class="span3 form-control">
<span v-if="errorinusername"> {{ errorinpassword}}</span>
</div>
<div class="form-group turms">
<input name="" type="checkbox" value="1" v-model="checked" id="terms"><label for="terms">I am over 18 and agree to the
Terms & Conditions</label>
<!--<label><input type="checkbox" name="terms">I am over 18 and agree to the Terms & Conditions.</label>-->
<input type="submit" :disabled="!checked" value="SIGN UP NOW" class="btn btn-primary w-100">
</div>
<div class="form-group">
<p>If you’d like to create a Moneyboy Profile click here.</p>
</div>
<div class="clearfix"></div>
</form>
</div>
</div>
</div>
</div>
<usersignup2component #recordadded="openusersignup2modal()"></usersignup2component>
</div>
<!--sction user-signup 1-->
</template>
<!--sript -->
<script>
Vue.component('usersignup2component', require('./UserSignup2Component.vue').default);
export default {
data(){
return {
username: '',
email:'',
password:'',
checked: false,
errorinusername: '',
errorinemail: '',
errorinpassword: '',
hidespan: true,
}
},
methods:{
addUser(){
axios.post('./api/user/signup', {
username:this.username,
email:this.email,
password:this.password
})
.then((response) =>{
this.$emit('recordadded');
})
.catch((error) => {
console.log(error.response);
this.hidespan = false;
this.errorinusername = error.response.data.errors.username;
this.errorinemail = error.response.data.errors.email;
this.errorinpassword = error.response.data.errors.password;
});
},
openusersignup2modal(){
console.log('okkkkkkkkkkkkkk');
}
},
mounted() {
console.log('UserSignUp1Component mounted.')
}
}
</script>
What I am doing wrong. I tried to console.log() on openusersignup2modal method to see, if it this function ever called or not. Found no activity on openusersignup2modal()
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
i want to show a popup message about to login the user. here iam using ajax function.
if the success: part is true i want to show the popup message. pls help me thanks in adv.
<button data-toggle="modal" data-target="#squarespaceModal" class="btn green btn-success" onclick="going('<?echo $user_id;?>','<?echo $event_id;?>')">Going</button>
<div class="modal fade" id="squarespaceModal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h3 class="modal-title" id="lineModalLabel">My Modal</h3>
</div>
<div class="modal-body">
<!-- content goes here -->
<form>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Password</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" id="exampleInputFile">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
<div class="modal-footer">
<div class="btn-group btn-group-justified" role="group" aria-label="group button">
<div class="btn-group" role="group">
<button type="button" class="btn btn-default" data-dismiss="modal" role="button">Close</button>
</div>
<div class="btn-group btn-delete hidden" role="group">
<button type="button" id="delImage" class="btn btn-default btn-hover-red" data-dismiss="modal" role="button">Delete</button>
</div>
<div class="btn-group" role="group">
<button type="button" id="saveImage" class="btn btn-default btn-hover-green" data-action="save" role="button">Save</button>
</div>
</div>
</div>
</div>
</div>
</div>
function going()
function going(user_id,event_id)
{
$.ajax({
url: "<?echo base_url()?>events/event_going",
type: 'post', // HTTP METHOD
data:
{user_id:user_id,event_id:event_id },
success: function(data)
{
if(data='true')
{
//pls check & add any suggsns
$('#squarespaceModal').dialog(data);
}
// document.getElementById('mysubmit').value="active";
}
});
}
controller
public function event_going()
{
$user_id=$this->input->post('user_id');
$event_id=$this->input->post('event_id');
$temp=$this->session->userdata('user');
$going=$this->EM->is_going($event_id,$user_id);
$going1=$this->EM->is_going1($event_id,$user_id);
if($temp=="")
{
echo "Please log in";
}
else if($going==$user_id)
{
echo "Already confirmed as going..";
}
else if($going1==$user_id)
{
echo "Are you sure you want to change... Press ok to continue";
$this->EM->event_updation($event_id,$user_id);
}
else
{
$data=array('event_id'=>$event_id,'ev_going'=>$user_id);
$this->EM->eventgoing($data);
}
}
What you can do is, instead of showing a new popup, you can get the content of popup from ajax. What i mean is, on click of a button, call ajax function, get the content and have a div inside the modal-body, for example
<div class="dynamic-data">
</div>
and in ajax success function do like this
success: function(data){
$(".dynamic-data").html(data);
}
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.