Laravel 5.2: Ajax login not working on live server, but working fine on localhost. Auth not working on live server - ajax

I am making a project in laravel 5.2
I have an issue.
this is a school management system where admin/teachers/students login to see their dashboard.
I have made a login page where username and email is given and users can login.
I have my own table for site users named "systemusers".
login is working fine on localhost but its not working on live server.
Auth is not working and users are redirected to login page again
JQUERY CODE:
function loginForm(formID){
//Empty validation errros
$(".errors").html("");
$(".failure").html("");
//Form error flag
var form_error = false;
var form_id = document.getElementById(formID);
var form_data = new FormData(form_id);
$("#"+formID+" input").each(function(key,value){
//Get ids
var id = $(this).attr('id');
if($.trim(this.value) == '' )
{
$("."+id).html("Empty");
form_error = true;
}
else{
if( id == 'username' )
{
var email = $("#username").val();
if( !isEmail(email) )
{
$("."+id).html("Email not Valid");
form_error = true;
}
}
else{
$("."+id).html("");
}
}
});
if( form_error === false )
{
$("#login-btn").prop("disabled", true);
//Run Ajax
$.ajax({
url:'loginFormSubmit',
method:'POST',
data:form_data,
cache:false,
contentType:false,
processData:false,
success:function(html)
{
//alert(html);
if($.trim(html) == 'ERROR-PASS')
{
$(".failure").html("Ivalid Password");
$("#login-btn").prop("disabled", false);
}
else if($.trim(html) == 'ERROR-EMAIL')
{
$(".failure").html("Email not Registered");
$("#login-btn").prop("disabled", false);
}
else
{
//alert(html);
window.location.replace("schoolsys/dashboard/");
}
}
});
}
return false;
}
LOGIN CONTROLLER FUNCTION CODE
public function postLoginUser()
{
//Get the email address posted via Ajax request.
$ajax_email = $_POST["email"];
$ajax_pass = $_POST["password"];
//Check if the email is registered.
$user = $this->systemuser->where("email", "=", $ajax_email)->first();
//If email is matched
if($user )
{
//Match the passwords
if( Hash::check($ajax_pass, $user->password) )
{
$loggedIn = Auth::login($user);
echo "LOGIN-SUCCESS";
}
else{
echo "ERROR-PASS";
}
}
else{
echo "ERROR-EMAIL";
}
DASHBOARD CONROLLER FUNCTION:
public function index()
{
if(!Auth::check())
{
return redirect()->route("login")->withErrors(["Please Login First"]);
}else{
return view("Dashboard");
}
}
ROUTES:
<?php
//Dashboard Route
Route::group(["middleware" => ["web", "auth"]], function(){
Route::get("/dashboard",
[
"as" => "dashboard",
"uses" => "DashboardController#index"
]);
});
//Login View Route
Route::group(["middleware" => ["web"]], function(){
Route::get("/login",
[
"as" => "login",
"uses" => "ajaxLoginController#loginView"
]);
//Ajax - Login Form
Route::post('/loginFormSubmit', 'ajaxLoginController#postLoginUser');
});
//Post Login Form - Double check
Route::post("/post-user-login",
[
"as" => "postLogin",
"uses" => "DashboardController#doubleCheckpostLoginUser"
]);
//Logout Route
Route::get("/logout",
[
"as" => "logout",
"uses" => "DashboardController#logout"
]);
//Add Admin Route
Route::get("/add-admin",
[
"as" => "add-admin",
"uses" => "DashboardController#addAdmin"
]);
//Ajax - Add Admin Form
Route::post("/create-admin", "DashboardController#ajaxPostAdmin")
?>

Related

How to solve SyntaxError: Unexpected token < in JSON at position 0 in Paypal checkout in Laravel

I am doing Paypal integration in Laravel. I have used composer require srmklive/paypal to install the srmklive/paypal package in this project.
When I press the PayPal button, I get this error:
Here is my code:
code from blade file:
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":100
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart();
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg); // Show a failure message (try to avoid alerts in production environments)
}
});
}
}).render('#paypal-button-container');
code from paymentController:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$price = Plan::getSubscriptionPrice($data['value']);
$description = Plan::getSubscriptionDescription($data['value']);
$order = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => $price
],
"description" => $description
]
]
]);
return response()->json($order);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
How can I solve this error?
The route api/paypal/order/create/ is returning/outputting text that is not JSON, such as an HTML error page or something else that begins with an HTML tag.
The route must only output JSON, and must contain a valid id from the PayPal API.

how to solve paypal login tab missing when integrate with paypal

I want to do paypal integration in Laravel. I have use composer require srmklive/paypal to install the srmklive/paypal package for my project. I get 404 error when I want to press the PayPal button. The popup paypal login tab will missing. Then I inspect the network I get the error like image given.
Here is my code:
class PaymentController extends Controller
{
public function create(Request $request){
$data = json_decode($request->getContent(), true);
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$plan = $provider->createOrder([
"intent" => "CAPTURE",
"purchase_units" => [
[
"amount" => [
"currency_code" => "USD",
"value" => "30"
],
"description" => "Item 1"
]
]
]);
return response()->json($plan);
}
public function capture(Request $request) {
$data = json_decode($request->getContent(), true);
$orderId = $data['orderID'];
$provider = \PayPal::setProvider();
$provider->setApiCredentials(config('paypal'));
$token = $provider->getAccessToken();
$provider->setAccessToken($token);
$result = $provider->capturePaymentOrder($orderId);
return response()->json($result);
}
}
Here is the code from blade file
paypal.Buttons({
createOrder: function(data, actions) {
return fetch('api/paypal/order/create/', {
method: 'post',
body:JSON.stringify({
"value":30
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
return orderData.id;
});
},
onApprove: function(data, actions) {
return fetch('/api/paypal/order/capture/', {
method: 'post',
body: JSON.stringify({
orderID: data.orderID
})
}).then(function(res) {
return res.json();
}).then(function(orderData) {
var errorDetail = Array.isArray(orderData.details) && orderData.details[0];
if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
return actions.restart(); // Recoverable state, per:
}
if (errorDetail) {
var msg = 'Sorry, your transaction could not be processed.';
return alert(msg);
}
});
}
}).render('#paypal-button-container');
The error show like image given.
Does anyone know how to solve it?
Does the route api/paypal/order/create/ exist on your server? From the error message, it's returning a 404.
The route must exist (no 404) and successfully output a JSON response with an id obtained from the PayPal API.

The Ajax pagination to my account not run

I would like to create an Ajax pagination of my articles in my account, here is my code that I created but it does not work I do not know how to do.
MyaccountController
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
I would like to have the javascript code
$(document).ready(function () {
$(document).on('click','.pagination a',function(e){
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
var url = $(this).attr('href');
$.ajax({
url: url,
method: 'GET',
data: {},
dataType: 'json',
success: function (result) {
if (result.status == 'ok'){
$('#userListingGrid').html(result.listing);
}else{
alert("Error when get pagination");
}
}
});
return false;
})
});
I would have a check on your controller for an ajax request like so:
public function viewProfile($username) {
if($username) {
$user = User::where('username', $username)->firstOrFail();
} else {
$user = User::find(Auth::user()->id);
}
if(request()->ajax()){
return response()->json(['user' => $user, 'articles' => $user->articles()->orderByDesc('created_at')->paginate(4);
}
return view('site.user.account', [
'user' => $user,
'articles' => $user->articles()->orderByDesc('created_at')->paginate(4),
]);
}
Then you don't have to load your view every time and you can let your javascript functions take care of the DOM manipulating of the results. Not sure if that's what you are looking for. I know that you would probably need a {{$articles->links()}} at the end of your view to go through each page.

Ajax successful when laravel authentication fails

I have a problem I have two forms on regular form and one ajax processed form. The regular form works as needed but the ajax form passes as successful even when authentication of the server side fells.
My loginHandler function is below
public function handleLogin(Request $request) {
// init auth boolean to false
$auth = false;
// run validation rules
$validator = User::validation($request->all(), User::$login_validation_rules, User::$login_error_messages);
// get credentials
$credentials = $request->only('email','password');
if($validator->fails()) {
return back()
->withErrors($validator)
->withInput();
}
$credentials = array_merge($credentials,['activated' => 1]);
// get remember from request
$remember = $request->has('remember');
if (\Auth::attempt($credentials, $remember)) {
$auth = true;
}
if($request->ajax()) {
$response = response()->json([
'auth' => $auth,
'intended' => \URL::route('home')
]);
return $response;
}
return redirect()->intended('/');
}
My ajax code is this
$('#login-nav').validate({
rules : {
email : {
required : true,
email : true
},
password : {
required : true
}
},
messages : {
email : {
required : '<div class="alert-danger alert-validation">Email is a required field.</div>',
email : '<div class="alert-danger alert-validation">Please enter a valid Email.</div>'
},
password : {
required : '<div class="alert-danger alert-validation">Password is a required field.</div>'
}
},
submitHandler: function (form){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('value')
},
type: $(form).attr('method'),
url: $(form).attr('action'),
data: $(form).serialize(),
dataType: 'json',
success: function (data) {
var html = '<div class="alert alert-success">Login Successful</div>';
$('#loginMsg').html(html);
return window.location = '/';
},
error: function (data) {
var html = '<div class="alert alert-danger">Email/Password is invalid</div>';
$('#loginMsg').html(html);
}
});
return false;
}
I would like to have the same behavior as my regular non ajax form. but instead of going to error in my ajax it's going to success. Any help would be greatly appreciated.
Auth::attempt will return you true or false, by default if you return a response()->json() without the 2nd parameter, it will be default to 200 (success). So based on the Auth::attempt you should either return 400 if it fails to login, then it should go into your ajax's error function.
$auth = \Auth::attempt($credentials, $remember);
if($request->ajax()) {
$responseCode = 200;
if( ! $auth) {
$responseCode = 400;
}
$response = response()->json([
'auth' => $auth,
'intended' => \URL::route('home')
], $responseCode);
return $response;
}

Username Available Check Using Laravel 5 in Ajax

Username available check in my register form if I am enter the username after loader.gif is loading but I am not getting the result for username available or not.. give me any suggestion
This is My Controller:
public function name()
{
$username = Input::get('username');
$users = DB::table('user')
->where('username', $username)
->first();
if ( $users !== null )
{
return true;
}
return false;
return view('test/username');
}
This is My Route:
Route::get('test/name', 'PageController#name');
This is My Blade Template Ajax:
<script type="text/javascript">
$(document).ready(function(){
$("#username").change(function(){
$("#message").html("<img src='../images/loader.gif' /> checking...");
var username=$("#username").val();
//alert(username);
$.ajax({
type:"post",
dataType: "json",
url :"{{URL::to('test/name') }}",
data: {username: username},
success:function(data){
if(data==0){
$("#message").html("<img src='../images/yes.png' /> Username available");
}
else{
$("#message").html("<img src='cross.png' /> Username already taken");
}
}
});
});
});
ajax is not response to the controller this is my problem
This is because you need to send json using the response() method from the controller to your view file.
Try out this way:
Controller:
public function name(Request $request)
{
// your validation logic ..
$userFound = User::find($request->input('username'))
if($userFound !== null) {
return response([
'status' => 'failed',
'message' => 'User Not Found'
]);
}
return response([
'status' => 'success',
'message' => 'User Found'
]);
}
And then update your success method of AJAX handler:
$.ajax({
// ..
success: function(receivedData) {
console.log(receivedData);
}
// ..
});

Resources