i have a login form to login a user i want to know about how to get laravel response in ajax success function. if submit the form i was got a object('status':'msg') in http://127.0.0.1:8000/login page. but i want to just redirect user correct page after login with macing alert. please help me to learn laravel with ajax function.
form
<form id="loginForm" method="POST" action="{{ route('login') }}">
#csrf
<input id="email" type="email" class="form-control name="email" value="{{ old('email') }}"
required autocomplete="email" autofocus>
<input id="password" type="password" class="form-control name="password" required
autocomplete="current-password">
<button type="submit" class="btn btn-primary">LOGIN</button>
</form>
ajax: after document ready
$('#loginForm').submit(function(e){
e.preventDefault();
var formInput = $(this);
$.ajax({
type:'POST',
url: 'login',
data: formInput.serialize(),
dataType: 'json',
cache: false,
success:function(status){
if(status== "success"){
alert("your in");
}
},
error:function(status){
if(status== "error"){
alert("no data found");
}
}
})
});
Route:
Route::post('login','loginController#login')->name('loginData');
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Auth;
use Session;
class loginController extends Controller
{
public function login(Request $request){
$credentials = $request->only('email', 'password');
if (Auth::attempt($credentials)) {
// print_r($request->all());
session()->put('role', Auth::user()->Role);
$request->session()->flash('message', 'New customer added successfully.');
$request->session()->flash('message-type', 'success');
return response()->json(['status'=>'success']);
return back();
}else{
$request->session()->flash('message', 'you have entered an invalid email address or password. please try again');
$request->session()->flash('message-type', 'danger');
return response()->json(['status'=>'error']);
return back();
}
}
}
You can return more data in your AJAX response than just a status. If you wanted to, you could also return a location to redirect to like:
return response()->json([
'status' => 'success',
'redirect' => '/user/dashboard'
]);
Then in your javascript, when you get success, you can then do:
success: function(response) {
if(response.status === "success") {
alert("your in");
window.location.href = response.redirect;
}
},
Related
i am trying to update password in Laravel, password is updating but when i try to login it shows wrong details, i am not sure what i am doing wrong here.
public function passwordupdate(Request $request, $id)
{
$user = User::find($id);
// Column updating with incorrect Hash
$user->password = Hash::make($request->password);
$user->setRememberToken(Str::random(60));
$user->active = 0; // This value is updating correctly
$user->save();
return response()->json(['msg' => 'password updated']);
}
As I mentioned my request was posting a null value so I am adding Ajax code to figure why.
Ajax
$('.update_password').on('click', function (e) {
console.log('Update password clicked!')
e.preventDefault();
$.ajax({
type: "POST",
dataType: 'json',
data: $(this).serialize(),
url: "/users/" + $('#user_pwid').val(),
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (data) {
if (data.msg) {
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data.msg);
}
}
});
});
View/Blade
<form method="post" id="policy-form">
#csrf
<input type="hidden" value="">
<select name="name" id="user_pwid" class="form-control user_pwid border border-secondary border-dark" required>
<option selected value="">SELECT USER</option>
#foreach($users as $user)
<option value="{{$user->id}}"> {{$user->name}}</option>
#endforeach
</select>
<input type="password" name="password" id="password">
<button type="click" class="btn btn-danger btn-sm update_password rounded text-center" value="{{$user->id}}"
id="update-password"></button>
</form>
Try This:
Controller Code:
public function passwordupdate(Request $request,$id) {
$user = User::find($id);
if(!is_null($user)){
$user->password = Hash::make($request->password);
$user->setRememberToken(Str::random(60));
$user->active =0;
$user->save();
return response('success');
}
else{
return response('failed');
}
}
Ajax Code:
$('#update-password').on('click', function(e) {
e.preventDefault();
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
},
type: "post",
url: "/users/" + $('#user_pwid').val(),
data :{
password : $('#password').val(),
},
success: function (data) {
if(data == 'success'){
alert('password changed successfully');
$('#response').empty();
$(".toast").toast('show');
$('#response').append(data);
}
else{
alert('failed');
}
},
});
});
Try this it'll work
Does $request->password actually have the intended password? Are you sure you haven't written a mutator on the model that is double hashing the password?
Is there a good reason you're creating your own password reset controller instead of using the one that Laravel ships with? Also - you really don't want to send the password back to the user in JSON.
i receive the 500 (Internal Server Error) after make a ajax request on laravel 5.2.
as I can see what is wrong?
at some point I saw that there is a command that starts with tails, but can not find it.
thanks.
code:
html:
<form role="form" id="Login" >
{{ csrf_field() }}
<label >Correo electronico: </label>
<input id="correo" type="email" class="form-control" name="email" placeholder="Enter email">
<id id="emailError"></id>
<label >ContraseƱa:</label>
<input id="password" type="password" class="form-control" name="password" placeholder="Enter password">
<id id="passwordError"></id>
<button type="button" class="btn btn-default" id="Submit" onclick="LogIn(event)" >Iniciar sesion</button>
</form>
js:
function LogIn(event) {
event.preventDefault();
$.ajax({
type: 'post',
url: Login,
dataType: 'json',
data: {
email: $('#correo').val(),
password: $('#password').val(),
},
beforeSend: function()
{
$("#emailError").fadeOut();
$("#passwordError").fadeOut();
},
success: function (data) {
if (!data.success){
console.log(data);
if(typeof data.error.email !== 'undefined'){
$('#correo').css('border-color', 'red');
$('#emailError').fadeIn(10, function () {
$("#emailError").html(data.error.email);
})
}
if(typeof data.error.password !== 'undefined'){
$('#password').css('border-color', 'red');
$('#passwordError').fadeIn(10, function () {
$("#passwordError").html(data.error.password[0]);
})
}
}else{
console.log(data);
$('#LogIn').modal('hide');
}
}
});
}
Controller:
<?php
namespace App\Http\Controllers;
use App\Modals\Users;
use Illuminate\Http\Request;
use Validator;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use App\Modals\Users as user;
use Auth;
class UserController extends Controller
{
public function index()
{
return view('home');
}
/**
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function entrar (Request $request){
$validator= Validator::make($request->all(),[
'email' => 'required|email',
'password' => 'required|min:2',
]);
if ($validator->fails()){
return response()->json([
'success' => true,
'error' => $validator->errors()->toArray()
]);
}else{
return response()->json([
'success' =>true
]);
}
if (Auth::attempt(['email' => $request->email, 'password' => $request->password]))
{
return response()->json([
'success' => true
]);
}else
{
return response()->json([
'success' => false,
'error' => 'not login'
]);
}
}
}
log:
POST http://localhost:8000/Entrar 500 (Internal Server Error) jquery.min.js:4
send # jquery.min.js:4
ajax # jquery.min.js:4
LogIn # scripts.js:82
onclick # VM18805:87
i'm using ajax to send email so i my problem is if i dont have
{!! csrf_field() !!}
in view i will get the token missmatch error.If i add input hidden token in view i will get this error
Swift_RfcComplianceException in MailboxHeader.php line 348: Address in
mailbox given [] does not comply with RFC 2822, 3.6.2.
How can i fix it.Thanks for help.
here it's view
<form action="{{ url('/findpass')}}" method="POST" id="forgotpassForm">
{!! csrf_field() !!}
<div class="form-group">
<input class="form-control input-lg" placeholder="E-mail" name="emailForgot" type="email" id="emailForgot" required>
</div>
<input type="submit" class="btn btn-lg btn-primary btn-block" id="forgotpassBtn" value="Send email">
</form>
Ajax
$(document).ready(function() {
$('#forgotpassBtn').click(function() {
event.preventDefault();
var email=$("#emailForgot").val();
var _token = $("input[name='_token']").val();
$.ajax({
url: '/findpass',
type: 'POST',
data:{
email:email,
_token : _token
},
success:function(data) {
alert(data.mess);
$("#forgotpass")[0].reset();
},
error:function() {
alert("Error");
}
});
});
});
Controller
public function resetPass()
{
$emailForgot=Input::get('emailForgot');
$user= User::where('email', '=' , $emailForgot)->first();
$data=['username'=>$user -> username,'email'=>$user -> email,'token'=>$user -> remember_token];
Mail::send('ui.mail.reset',$data, function ($m) use ($user) {
$m->from('ngohungphuc95#gmail.com', 'Reset password');
$m->to($user->email, $user->full_name)->subject('Email reset password');
});
return response()->json(array('mess'=>'Mail send'));
}
Add the csrf without blade and add an id by yourself. Get the value of csrf value by id using jquery. Here is how you can do this.
Change {!! csrf_field() !!} to:
<input type="hidden" name="_token" value="{{ csrf_token() }}" id="token"/>
And Change this line of ajax code:
var _token = $("input[name='_token']").val();
To:
var _token = $('#token').val();
May be this is not the best way. But I solved my problem with this procedure.
You could also add a global csrf token to all ajax calls like this
$(document).ready(function(){
$.ajaxSetup({
headers: { 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content') },
});
});
Then just override the tokensMatch() method of the VerifyCsrfToken token to also look for the ajax header
protected function tokensMatch($request)
{
// If request is an ajax request, then check to see if token matches token provider in
// the header. This way, we can use CSRF protection in ajax requests also.
$token = $request->ajax() ? $request->header('X-CSRF-Token') : $request->input('_token');
return $request->session()->token() == $token;
}
After this all your ajax calls will automatically pass csrf checks and be secure.
Swift_RfcComplianceException in MailboxHeader.php line 348: Address in mailbox given [] does not comply with RFC 2822, 3.6.2.
The above error is because you haven't configured a from address in config/mail.php. It is set to null by default, but should be a valid email address:
'from' => ['address' => 'user#example.com', 'name' => null],
I need to create auth from any pages over ajax. If i'm send wrong login and empty pass(or vice versa) - will be return json errors (it's ok). If i'm send wrong login and wrong pass(or right login and path) - will be return redirect.
How to change backend for get response json anyway?
my frontend code js:
$("#authform").submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(data) {
console.log(data);
}, "json");
});
html:
<form id="authform" method="POST" action="{{ url('/auth/login') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<input type="email" name="email" value="{{ old('email') }}">
<input type="password" name="password">
<input type="checkbox" name="remember">
<button type="submit">Login</button>
</form>
routes.php:
Route::post('auth/login', 'Auth\AuthController#postLogin');
This is not an answer. First try this then we should
$('#authform').on('submit',function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
cache: false,
dataType: 'JSON',
url: $(#authform).attr("action"),
data: $('#authform').serialize(),
success: function(data) {
console.log(data);
},
});
return false;
});
And have you tried this link How to create AJAX login with Laravel
I'm sure there is a better solution for this problem, but what I did was:
Create a new route for loging in
Route::post('/login', 'Auth\AuthController#signIn');
In App\Http\Controllers\Auth\AuthController I added two new methods:
public function signIn(Request $request) {
$this->validateLogin($request);
$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 ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}
return $this->sendFailedLoginResponseJSON($request);
}
AND
protected function sendFailedLoginResponseJSON(Request $request)
{
return response()->json(['username' => $this->getFailedLoginMessage()], 422);
}
It's basically the same as the login method from AuthenticatesAndRegistersUsers trait, except for the last line, the login method uses
protected function sendFailedLoginResponse(Request $request)
{
return redirect()->back()
->withInput($request->only($this->loginUsername(), 'remember'))
->withErrors([
$this->loginUsername() => $this->getFailedLoginMessage(),
]);
}
which sends back a redirect with the error.
If you want both ajax and non-ajax, you can do
if($request->ajax()){
return $this->sendFailedLoginResponseJSON($request);
}
return $this->sendFailedLoginResponse($request);
in the new sign in method.
I am new in AJAX. but I am trying to learn How this is working.
I am using symfony2 with fos user bundle and I want implement AJAX to my login form.
so I was doing this :
login.html.twig
<script>
$('#_submit').click(function(e){
e.preventDefault();
$.ajax({
type : $('form').attr( 'method' ),
url : $('form').attr( 'action' ),
data : $('form').serialize(),
success : function(data, status, object) {
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
window.location.href = data.targetUrl;
}
}
});
</script>
<div id="tab-1" class="login_form">
<form action="{{ path("fos_user_security_check") }}" role="form" method="post">
<label for="username"><strong>User Name / Email Address</strong>
<input type="text" id="username" name="_username" value="{{ last_username }}" required="required" />
</label>
<label for="password"><strong>Password</strong>
<input type="password" id="password" name="_password" required="required" />
</label>
<label for="password"><strong>Remember Me</strong>
<input type="checkbox" id="remember_me" name="_remember_me" value="on" />
</label>
<input type="submit" class="submitBut" id="_submit" name="_submit" value="{{ 'security.login.submit'|trans({}, 'FOSUserBundle') }}" />
</form>
</div>
And when submit then go this file :-
<?php
namespace XXXX\UserBundle\Handler;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Router;
use Symfony\Component\Security\Core\SecurityContext;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector;
class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
protected $router;
protected $security;
protected $userManager;
protected $service_container;
public function __construct(RouterInterface $router, SecurityContext $security, $userManager, $service_container)
{
$this->router = $router;
$this->security = $security;
$this->userManager = $userManager;
$this->service_container = $service_container;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
if ($request->isXmlHttpRequest()) {
$result = array('success' => true);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
else {
// Create a flash message with the authentication error message
$request->getSession()->getFlashBag()->set('error', $exception->getMessage());
$url = $this->router->generate('fos_user_security_login');
return new RedirectResponse($url);
}
return new RedirectResponse($this->router->generate('anag_new'));
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception) {
$translator = new Translator('fr_FR');
//$result = array(
// 'success' => false,
// 'function' => 'onAuthenticationFailure',
// 'error' => true,
// 'message' => $this->translator->trans($exception->getMessage(), array(), 'FOSUserBundle')
//);
$result = array('success' => false);
$response = new Response(json_encode($result));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
When submit the form then show me in login_check url:
{"success":false}
But I want when result false then return same form where I was trying to login(I mean same popup div)?
What's wrong my code ajax or action return ?
Or I am return correct ?
window.location will reload the entire page. That's not the desired result I suppose since you are using AJAX ( the hole point of AJAX is to not reload the page) instead you could display an error message if the login is not successful.
I suggest you add an error div in your html form
<div class='error' style="display:none" > ooups an erro occured </div>
and then in the ajax call just show it or add a significant message error :
if (data.sucess == false) {
$('.tab-1').prepend('<div />').html(data.message);
} else {
$('.error').show();
}