Форма входа с Ajax с использованием Laravel 5.2

Я пытаюсь создать форму входа с помощью Ajax, используя Laravel 5.2 Auth.

$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

$('#login').on('click',function(e){
e.preventDefault();

var formData = {
email: $('#email').val(),
password: $('#password').val(),
}
$.ajax({
type: "POST",
url: "/login",
data: formData,
success: function (data) {
location.reload();
},
error: function (data) {

}
});

});

})enter code here

Функция входа в Laravel по умолчанию:

public function login(Request $request)
{
$this->validateLogin($request);

// If the class is using the ThrottlesLogins trait, we can automatically throttle
// the login attempts for this application. We'll key this by the username and
// the IP address of the client making these requests into this application.
$throttles = $this->isUsingThrottlesLoginsTrait();

if ($throttles && $lockedOut = $this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);

return $this->sendLockoutResponse($request);
}

$credentials = $this->getCredentials($request);

if (Auth::guard($this->getGuard())->attempt($credentials, $request->has('remember'))) {
return $this->handleUserWasAuthenticated($request, $throttles);
}

// If the login attempt was unsuccessful we will increment the number of attempts
// to login and redirect the user back to the login form. Of course, when this
// user surpasses their maximum number of attempts they will get locked out.
if ($throttles && ! $lockedOut) {
$this->incrementLoginAttempts($request);
}

return $this->sendFailedLoginResponse($request);
}

/ вход возвращать индексную страницу в качестве ответа.
Мне нужен ответ JSON о сообщениях об ошибках или об успехе.
Говорят, что изменение основных функций Laravel не рекомендуется. Тогда как я могу получить это?

1

Решение

Как я понял Ваш пример кода является просто копией AuthenticatesUser черта характера.

Поэтому, чтобы избежать больших изменений и заставить его работать, просто замените код контроллера по умолчанию в app/Http/Controllers/LoginController.php с этим:

<?php

namespace App\Http\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class LoginController extends Controller
{
public function __construct()
{
$this->middleware('guest', ['except' => 'logout']);
}

protected function username() {
return 'email';
}

public function login(Request $request)
{
$credentials = $request->only($this->username(), 'password');
$authSuccess = Auth::attempt($credentials, $request->has('remember'));

if($authSuccess) {
$request->session()->regenerate();
return response(['success' => true], Response::HTTP_OK);
}

return
response([
'success' => false,
'message' => 'Auth failed (or some other message)'
], Response::HTTP_FORBIDDEN);
}

public function logout(Request $request)
{
Auth::logout();
$request->session()->flush();
$request->session()->regenerate();

return redirect('/');
}
}

JS часть может сохранить то же самое:

$.ajax({
type: "POST",
url: "/login",
data: formData,
dataType:'json',
success: function (response) {
if(response.success) {
location.reload();
}
},
error: function (jqXHR) {
var response = $.parseJSON(jqXHR.responseText);
if(response.message) {
alert(response.message);
}
}
});

но я лично предпочитаю обрабатывать не кнопку, которая отправляет, а форму в целом, чтобы предотвратить это, когда пользователь нажимает enter кнопку, чем просто нажмите на кнопку входа.

проверьте этот пример:

HTML часть:

<form class="login" action="{{ url('/login') }}" method="post" data-type="json">
<input type="text" name="email">
<input type="password" name="password">
<button type="submit">login</button>
</form>

JS часть:

$(function() {

$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});

$('form.login:first').on('submit', function(e){
e.preventDefault();

var $this = $(this);

$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: $this.serializeArray(),
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
location.reload();
}
},
error: function (jqXHR) {
var response = $.parseJSON(jqXHR.responseText);
if(response.message) {
alert(response.message);
}
}
});
});

});
2

Другие решения

Вы можете попробовать добавить в jquery

dataType: 'JSON'

или попробуйте сохранить в сеансе и использовать

Redirect::back()

или же

return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
1

Примерьте вот это

use Validator;
use Auth;public function postUserLogin(Request $request) {
$credentials = array_trim($request->only('email', 'password'));
$rules = ['email' => 'required|email|max:255',
'password' => 'required'
];

$validation = Validator::make($credentials, $rules);
$errors = $validation->errors();
$errors = json_decode($errors);
if ($validation->passes()) {
if (Auth::attempt(['email' => trim($request->email),
'password' => $request->password,
], $request->has('remember'))) {return response()->json(['redirect' => true, 'success' => true], 200);
} else {
$message = 'Invalid username or password';

return response()->json(['password' => $message], 422);
}
} else {
return response()->json($errors, 422);
}
}
1

Добавить следующим образом

  /**
* Handle a login request to the application.
*
* @param  \Illuminate\Http\Request  $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response|\Illuminate\Http\JsonResponse
*
* @throws \Illuminate\Validation\ValidationException
*/
public function login(Request $request)
{
$this->validateLogin($request);

if ($this->hasTooManyLoginAttempts($request)) {
$this->fireLockoutEvent($request);
return response()->json( $this->sendLockoutResponse($request));
}
if ($this->attemptLogin($request)) {
return response()->json( $this->sendLoginResponse($request) );
}

$this->incrementLoginAttempts($request);
return response()->json($this->sendFailedLoginResponse($request));
}
0
По вопросам рекламы ammmcru@yandex.ru
Adblock
detector