2017-02-06 7 views
0

Im пытается сделать логин в laravel через ajax, поэтому я хочу, чтобы эта функция возвращала только объект json в случае ошибок функция возвращает json только тогда, когда вход (адрес электронной почты или пароль пуст), но я вставлять неверные данные в купил темы, функция возвращает html-страницу с ошибками; но я хочу вернуть только эти ошибки без HTML-страницы (я предполагаю, что это доза return response()->back()->withErrors('errors'))laravel login через ajax

мой код Js:

$('#form-login').submit(function(event) { 
     event.stopPropagation(); // Stop stuff happening 
     event.preventDefault(); // Totally stop stuff happening    
     var data = { 
      email : $('#login_email').val(), 
      password : $('#login_password').val(), 
     } 

     $.ajax({ 
      url: '/login', 
      type: 'post', 
      data: data, 
      success:function(data, textStatus, jqXHR) { 

       if (jqXHR.getResponseHeader('Content-Type').includes('json')) { 

         window.location.reload(); 

        } 
      }, 
      error:function(data) { 
       // console.log(data['email']) 
       // console.log(data.email) 
       if(data.responseJSON.email){ 
         $('#Email-help-block').html(data.responseJSON.email[0]) 
        }else{ 
         $('#Email-help-block').html('') 
        } 
       if(data.responseJSON.password){ 
         $('#Password-help-block').html(data.responseJSON.password[0]) 
        }else{ 
         $('#Password-help-block').html('') 
        } 
      }, 
     }) 


    }); 

функция Логин:

public function login(Request $request) 
{ 
    $this->validateLogin($request); // this is where it returns errors 
    // 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); 
} 

ответ

0

Мое решение этой проблемы проблема в том, что:

<body> 
    <main class="container small"> 
     <div class="middle"> 
     <body> 
    <main class="container small"> 
     <div class="middle"> 
      <img 
      <br> 
      <div class="error valign-wrapper" style=" border: 2px solid red; border-radius: 7px;" hidden> 
       <h5 class="center-align"> Helaas zijn uw inloggegevens incorrect </h5> 
      </div> 
      <form method="POST" action="/api/v1/login" class="login"> 
       {!! csrf_field() !!} 
       <input type="text" name="email" class="emailaddress" placeholder="Je e-mailadres..." style="background-image: url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII=&quot;); cursor: auto;" autocomplete="off"> 
       <input type="password" name="password" class="password" placeholder="Je wachtwoord..." style="background-image: url(&quot;data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR4nGP6zwAAAgcBApocMXEAAAAASUVORK5CYII=&quot;); cursor: auto;" autocomplete="off"> 
       <div class="left"> 
        <a href="/password/reset">Wachtwoord vergeten?</a> 
        <a href="/">← Terug</a> 
       </div> 
       <div class="right"> 
        <input type="submit" class="button" value="Log in"> 
       </div> 
      </form> 
     </div> 
    </main> 
</body> 
@include('footer') 
@push('scripts') 
    <script> 
    $('form.login').submit(function(e) { 
     $form = $(this); 
     e.preventDefault(); 
     $.post(window.location.origin + $form.attr('action'), $form.serialize()) 
     .done(function(data) { 
      window.location.href = 'account'; 
     }) 
     .fail(function() { 
      $('.error').show(); 
     }); 
    }); 
    </script> 
@endpush 

Это HTML-код с скрытой возможностью (или вы можете показать это с помощью j st ajax) при ошибке. Мой javascript помещается в стек javascript внизу.

 Смежные вопросы

  • Нет связанных вопросов^_^