see the server error after ajax request with laravel - ajax

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

Related

Multi AJAX Request in Laravel

Goodtime
I write this code but when i send for database only submit one query "sad" !
çi use
$request->has('happy') or ... no working
Can anyone help me?
for sample
**$request->has('happy') ** submit 'happy' or **$request->has('love') ** submit 'love'
I'm tired of searching
thanks to stackoverflow and members
<form method="post">
{{csrf_field()}}
<button type="submit" value="happy" id="happy" class="border-0 btn-submit">
<img src="/assets/images/reactions/happy.png" />
</button>
<button type="submit" value="angry" id="angry" class="border-0 btn-submit">
<img src="/assets/images/reactions/angry.png" />
</button>
<button type="submit" value="ill" id="ill" class="border-0 btn-submit">
<img src="/assets/images/reactions/ill.png" />
</button>
<button type="submit" value="love" id="love" class="border-0 btn-submit">
<img src="/assets/images/reactions/in-love.png" />
</button>
<button type="submit" value="quiet" id="quiet" class="border-0 btn-submit">
<img src="/assets/images/reactions/quiet.png" />
</button>
<button type="submit" value="sad" id="sad" class="border-0 btn-submit">
<img src="/assets/images/reactions/sad.png" />
</button>
<!-- <input type="text" name="studentName" id="studentName" class="form-control" placeholder="please type in your name"> -->
<input type="hidden" value="{{$article->id}}" id="post_id">
<input type="hidden" name="_token" value="{{csrf_token()}}">
</form>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-submit").click(function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var sad = $("#sad").val();
var quiet = $("#quiet").val();
var love = $("#love").val();
var ill = $("#ill").val();
var angry = $("#angry").val();
var happy = $("#happy").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: {
post_id: post_id,
sad: sad,
quiet: quiet,
love: love,
ill: ill,
angry: angry,
happy: happy
},
success: function(data) {
alert(data.success);
}
});
});
</script>
</div>
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Reaction;
use Illuminate\Support\Facades\Auth;
class AjaxController extends Controller
{
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequest()
{
return view('ajaxRequest');
}
/**
* Create a new controller instance.
*
* #return void
*/
public function ajaxRequestPost(Request $request, Reaction $reaction)
{
$input = $request->all();
\Log::info($input);
if ($request->ajax()) {
if (!Auth::user()) { // Check is user logged in
$must_login = "you must login";
return response()->json(['success' => $must_login]);
} else {
$date = date('Y-m-d');
$user_id = Auth::user()->id;
$output = "Your reaction Submited";
$post_id = $request->input('post_id');
// Checker
$checker = Reaction::select('*')->where([
['post_id', '=', $post_id],
['user_id', '=', $user_id],
['date', '=', $date]
])->first();
if ($checker == null) {
if ($request->has('sad') == true) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'sad',
'date' => $date,
]);
} elseif ($request->has('love')) {
Reaction::create([
'user_id' => $user_id,
'post_id' => $post_id,
'reaction' => 'love',
'date' => $date,
]);
} else {
echo "fuck";
}
return response()->json(['success' => $output]);
} else {
return response()->json(['success' => 'You Befor Submited Your Rection']);
}
}
}
}
}
This should work:
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$("form").on('submit', function(e) {
e.preventDefault();
var post_id = $("#post_id").val();
var reaction = $(".btn-submit").val();
$.ajax({
type: 'POST',
url: "{{ route('ajaxRequest.post') }}",
data: { post_id, reaction },
success: function(data) {
alert(data);
}
});
});
public function ajaxRequestPost(Request $request)
{
$data = $request->all();
return response()->json($data);
}

how to get laravel response the same page after login with ajax?

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;
}
},

Laravel client authentification with external Laravel passport lumen api

I have been looking online but i can't find any way of doing it. Let me explain, i have an API (Laravel passport on lumen), i tested it with Postman, i get my access token with oauth, everything is fine. Now i have another Laravel application and i want to know how i can keep all my authentification stuff using the API to login. I have seen lot of apps that actualy retrieve an api_token and they use 'Auth::user()->where('api_token', $token)'. But i find this wrong because i don't want my client to have access to the database, i want every request to the database to be handled by the API. Is that possible?
Let say you want to login to a laravel backend app via api. make sure you install guzzle.
Route(api): Route::POST('/login', 'AuthController#login')
Controller: AuthController.php
public function login(Request $request)
{
$this->validate($request, [
'email' => 'required|email',
'password' => 'required|string',
]);
$http = new \GuzzleHttp\Client;
try {
$response = $http->post(config('services.passport.login_endpoint'), [
'form_params' => [
'grant_type' => 'password',
'client_id' => 'your client_id',
'client_secret' => 'your client_secret',
'username' => $request->email,
'password' => $request->password,
// 'scope' => '',
],
]);
return $response->getBody();
} catch (\GuzzleHttp\Exception\BadResponseException $e) {
if ($e->getCode() == 401) {
return response()->json(['message' => 'This action can\'t be perfomed at this time. Please try later.'], $e->getCode());
} else if ($e->getCode() == 400) {
return response()->json(['message' => 'These credentials do not match our records.'], $e->getCode());
}
return response()->json('Something went wrong on the server. Please try letar.', $e->getCode());
}
}
In your front-end app for example vuejs, even laravel using vue component. As you can see, i'm using boostrap-vue but feel free to use the regular html elements
<template>
<div>
<form #submit.prevent="login()">
<b-form-group label="Email">
<b-input placeholder="E-Mail" class="ml-1" v-model="form.email" type="email" name="email" :class="{ 'is-invalid': form.errors.has('email') }"/>
<has-error :form="form" field="email"></has-error>
</b-form-group>
<b-form-group>
<div slot="label" class="d-flex justify-content-between align-items-end">
<div>Password</div>
Forgot password?
</div>
<b-input v-model="form.password" type="password" name="password" :class="{ 'is-invalid': form.errors.has('password') }" />
<has-error :form="form" field="password"></has-error>
</b-form-group>
<div class="d-flex justify-content-between align-items-center m-0">
<b-check v-model="form.rememberMe" class="m-0">Remember me</b-check>
<b-btn type="submit" variant="primary">Sign In</b-btn>
</div>
</form>
</div>
<template>
<script>
export default ({
name: 'pages-authentication-login-v2',
metaInfo: {
title: 'Login'
},
state: {
token: localStorage.getItem('access_token'),
},
mutations: {
login(state, token) {
state.token = token
},
},
data: () => ({
form: new Form({
email: '',
password: '',
})
}),
methods: {
login(){
this.form.post('/api/login')
.then((response) =>{
const token = response.data.access_token
localStorage.setItem('access_token', token)
// console.log(response);
this.$router.push('/dashboard');
})
.catch((error)=>{
this.$toasted.error('Ooops! Something went wrong', {
icon : "warning",
theme: "bubble",
closeOnSwipe: true,
position: "top-right",
duration : 5000,
singleton: true,
})
});
},
}
})
</script>

laravel 5 ajax authentification

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.

methodNotAllowed(array('GET', 'HEAD')) in RouteCollection.php laravel 5.0

I want to login as I submit the form but I am getting an error.
The form code is as follows:
{!! Form::open() !!}
{{ $errors->first("parentPassword") }}<br />
<div>
<legend>Parent</legend>
Email<br>
<input type="email" id="email" name="parentEmail" required>
<br>
Password<br>
<input type="password" name="parentPassword">
<br><br>
</div>
{!!Form::submit('Submit',array('class' => 'btn btn-outline btn-primary')) !!} </fieldset>
{!! Form::close() !!}
The controller code is as follows:
App\Http\Controllers;
use Illuminate\Support\Facades\Redirect;
class loka extends Controller
{
public function login()
{
if ($this->isPostRequest()) {
$validator = $this->getLoginValidator();
if ($validator->passes()) {
$credentials = $this->getLoginCredentials();
if (Auth::attempt($credentials)) {
return redirect()->intended('/');
}
return Redirect::back()->withErrors([
"parentPassword" => ["Credentials invalid."]
]);
} else {
return Redirect::back()
->withInput()
->withErrors($validator);
}
}
return view("signup.index");
}
protected function isPostRequest()
{
// return Request::isMethod('post');
}
protected function getLoginValidator()
{
return Validator::make(Request::all(), [
"parentEmail" => "required",
"parentPassword" => "required"
]);
}
protected function getLoginCredentials()
{
return [
"parentEmail" => Request::input("parentEmail"),
"parentPassword" => Request::input("parentPassword")
];
}
}
The route is as follows:
Route::patch("/index", [
"as" => "login/index",
"uses" => "loka#login"
]);

Resources