I have this ajax function that requests this route to login, but I want the redirection to be directly on the controller if the login is successful.
My ajax request:
$('#btn_login').on('click', function () {
var name = $('#name').val();
var pass = $('#pass').val();
$.ajax({
type: "POST",
url : "login",
dataType: "JSON",
data: {
name,
pass
},
success: function (data) { },
error: function (data) {
alert('Login Error ');
}
});
return false;
});
My route.php:
Route::post('/login', 'LoginController#authenticate');
My LoginCOntrol.php:
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'pass');
$email = $credentials['email'];
$password = $credentials['pass'];
if (Auth::attempt(['email' => $email, 'password' => $password])) {
return view('login.homepage')
}else{
return redirect()->back();
}
}
Try on ajax:
success: function (data) {location.href=data.url;},
And on Controller
Change
return view('login.homepage')
to
return response()->json(['url'=>route('homepage')]);
Hope this will answer your question.
Related
I have login modal in view and want to login with Ajax in Laravel 5.6. Ajax returns me 'Success' message, but when I refresh window location with JS, User data is not accessible from blade template. Here is my code
My Controller
protected function authenticated(Request $request)
{
$auth = false;
if (Auth::attempt(['email' => $request->email, 'password' => $request->password])) {
$auth = true; // Success
$request->session()->put('current_user',Auth::user());
}
if ($request->ajax()) {
return response()->json([
'success' => true,
'auth' => $auth,
'intended' => URL::previous()
]);
} else {
return redirect()->intended(URL::route('contact'));
}
return redirect(URL::route('login_page'));
}
My Ajax
$(document).ready(function () {
var loginForm = $("#loginForm");
loginForm.submit(function(e){
e.preventDefault();
var formData = loginForm.serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url:"{{ route('ajax_login') }}",
type:'POST',
data:formData,
success:function(data){
// console.log(data);
window.location.href = '/'
},
error: function (data) {
console.log('failed');
}
});
});
My Route
Route::post('/user-login', 'Auth\LoginController#authenticated')->name('ajax_login');
It's because when you refresh using window.location.reload all the javascript files will be reloaded and the variables will be cleaned.
You can store your data in the local storage window.localStorage.putItem('key', object) or directly use your data using jQuery, it depends on yout need.
Hopes it helps.
I try to create login form with Ajax using 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 default login function:
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);
}
/login return index page as a response.
I need json response about error messages or success message.
It is said that changing Laravel core functions is not advisable. Then how can I get it?
As I understood Your code example is just copy of AuthenticatesUser trait.
So to avoid big changes and make it work, just replace default controller code in app/Http/Controllers/LoginController.php with this:
<?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 part can keep the same:
$.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);
}
}
});
but I personally prefer to handle not the button that does submit, but the form generally, to prevent this happen when user press enter button than just click on the login button.
check this example:
html part:
<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 part:
$(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);
}
}
});
});
});
You can try adding in jquery
dataType: 'JSON'
or Try to store in Session and use
Redirect::back()
or
return redirect($this->loginPath())
->withInput($request->only('email', 'remember'))
->withErrors([
'email' => $this->getFailedLoginMessage(),
]);
Please try this one
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);
}
}
Add as follows
/**
* 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));
}
I am working on a project with CI and Ajax. Since, I'm working with ajax after a long time, I am having some issues in debugging. I have written this code. In which i am sending data to to controller function login. Please guide me regarding how to check whether the data is reaching controller, and model. And also on how to return data from model to controller and from controller to view.
My Ajax code is as follows:
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert('Ajax Success');
}, error: function () {
alert('Ajax Error');
}
});
}
});
Controller home.php Code is as follows:
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
return $data;
}
and Model Dis_model.php code is as follows:
function check_user($uname, $pwd) {
$this->db->select('*');
$this->db->where('uname', $uname);
$this->db->where('pwd', $pwd);
$query = $this->db->get('users');
return $query->result();
}
All positive suggestions are welcomed.
Thanks in advance.
Change In Controller:
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
echo $uname;
exit;
}
Change in ajax:
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert(response);
}, error: function () {
alert('Ajax Error');
}
});
}
});
Same in modal
Change in Controller
public function login() {
$uname = $this->input->post('uname');
$pwd = $this->input->post('pwd');
$data['userinfo'] = $this->dis_model->check_user($uname,$pwd);
echo json_encode($data['userinfo']);
die;
}
Change in ajax
$('#login').click(function () {
if (($('#inputUname').val() === "") || ($('#inputPassword').val() === "")) {
alert('please username and password');
} else {
var data = {
'uname': $('#inputPassword').val(),
'pwd': $('#inputPassword').val()
};
$.ajax({
type: "POST",
url: base_url + "home/login",
data: data,
dataType: "json",
success: function (response)
{
alert(response);
}, error: function () {
alert('Ajax Error');
}
});
}
});
controller
).controller('LoginController',
[
'$scope',
'dataService',
'$location',
'$window',
function ($scope, dataService, $location,$window){
$scope.check_login=function($event,userID,passwd)
{
dataService.login(userID,passwd).then
(
function (response){
$scope.loginCount = response.rowCount + 'account Record';
$scope.loginConfirm = response.data;
console.log(response.data);
},
function (err) {
$scope.status = 'unable to connect to data' + err;
});
// $scope.reloadRoute = function () {
// $location.path('/#');
// $window.location.reload()
// }//end of reload route fnction
}//end of function check_login
}
]
Services.js
this.login = function (userID, passwd) {
var defer = $q.defer(),
data = {
username: userID,
password: passwd
};
$http.post(urlBase, {
params: data,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
cache: true
})
. // notice the dot to start the chain to success()
success(function (response) {
defer.resolve({
data: response.login.Result, // create data property with value from response
rowCount: response.login.RowCount // create rowCount property with value from response
});
})
. // another dot to chain to error()
error(function (err) {
defer.reject(err);
});
// the call to getCourses returns this promise which is fulfilled
// by the .get method .success or .failure
return defer.promise;
};
index.php
if (isset($_POST['username']) && isset($_POST['password'])) {
$useremail = $_POST['username'];
$password = $_POST['password'];
$service = new FilmsService();
$result = $service->login($useremail, $password);
echo $result;
} else {
echo "Cant Find The Data";
}
Currently i got 3 file name controller,service.js and index.php , service.js is u to pass the data to the php side, but when i try to get the username and password in the php side, it will be error.Cant get the username and password.
How to solve it? is it my code error?
Try this in place of your $http.post:
$http({
method: 'POST',
url: urlBase,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: data
});
I am working with Laravel 4 and I want to perform validation with Ajax. I have 2 main problems:
1. The URL at Ajax is static, which means that if I have my app online I should put the URL for online and locally doesn't works
2. my route is insur_docs/{id} how should be URL for this?
jQuery('form#insur_docs_update').submit(function()
{
jQuery.ajax({
url: "http://localhost:8080/insur_docs/{id}", //my url I don't know how to put it
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
})
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
var arr = data.errors;
jQuery.each(arr, function(index, value)
{
if (value.length !== 0)
{
$("#validation-div").addClass('alert alert-danger');
document.getElementById("validation-div").innerHTML += '<span class="glyphicon glyphicon-warning-sign"></span>' + value + '<br/>';
}
});
jQuery('#ajax-loading').hide();
}
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('No response from server');
});
return false;
});
routes.php
Route::get('insur_docs/{id}', 'Insur_DocController#edit');
controller
public function update($id) {
Input::flash();
$data = [
"errors" => null
];
$rules = array(
"ownership_cert" => "required",
"authoriz" => "required",
"drive_permis" => "required",
"sgs" => "required",
"tpl" => "required",
"kasko" => "required",
"inter_permis" => "required",
);
$validation = Validator::make(Input::all(), $rules);
if ($validation->passes()) {
$car_id = DB::select('select car_id from insur_docs where id = ?', array($id));
$data = InsurDoc::find($id);
$data->ownership_cert = Input::get('ownership_cert');
$data->authoriz = Input::get('authoriz');
$data->drive_permis = Input::get('drive_permis');
$data->sgs = Input::get('sgs');
$data->tpl = Input::get('tpl');
$data->kasko = Input::get('kasko');
$data->inter_permis = Input::get('inter_permis');
$data->save();
return Redirect::to('car/' . $car_id[0]->car_id);
} else {
if (Request::ajax()) {
$response_values = array(
'validation_failed' => 1,
'errors' => $validation->errors()->toArray()
);
return Response::json($response_values);
}
}
}
Use laravel's url generator helper to create your form's action:
<form action="{{ URL::action('Insur_DocController#edit', $id) }}" method="post">
You can access it in your javascript:
jQuery('form#insur_docs_update').submit(function()
{
var url = $(this).attr("action");
jQuery.ajax({
url: url,
type: "post",
data: jQuery('form#insur_docs_update').serialize(),
datatype: "json",
beforeSend: function()
{
jQuery('#ajax-loading').show();
jQuery(".glyphicon-warning-sign").hide();
}
});
}
EDIT
You're second problem is that you're redirecting in response to the ajax call, and that does not redirect the page. You'll need to return the url and do the redirect in javascript like this.
Controller:
return Response::json(["redirect_to" => 'car/' . $car_id[0]->car_id]);
JS (just the relevant part):
.done(function(data)
{
$('#validation-div').empty()
if (data.validation_failed === 1)
{
// your code
} else {
window.location = data.redirect_to;
}
})
var myUrlExtension = "whatever.php"
and inside the ajax
url: "http://localhost:8080/insur_docs/" + myUrlExtension