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;
}
Related
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.
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.
My console shows this error whenever I try to update my form using my ajax code:
PUT http://127.0.0.1:8000/clinical/bbr-category-configuration-update/1 500 (Internal Server Error)
Route:
Route::put('/bbr-category-configuration-update/{category_id}', [BBRCategoryConfigurationController::class,'update']);
Ajax:
$(document).on('click', '.update_category', function (e){
e.preventDefault();
var cat_id = $('#edit_cat_id').val();
var update_data = {
'category_name' : $('#edit_category_name').val(),
'category_description' : $('#edit_category_description').val(),
}
//token taken from laravel documentation
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: "PUT",
url: "/clinical/bbr-category-configuration-update/"+cat_id,
data: update_data,
dataType: "json",
success: function (response){
// console.log(response);
if(response.status == 400) {
$('#category_formCheckUpdate').html("");
$('#category_formCheckUpdate').addClass('alert alert-danger');
$.each(response.errors, function (key, err_values) {
$('#category_formCheckUpdate').append('<li>'+err_values+'</li>');
});
} else if(response.status == 404) {
$('#category_formCheckUpdate').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
} else {
$('#category_formCheckUpdate').html("");
$('#category_notif').html("");
$('#category_notif').addClass('alert alert-success');
$('#category_notif').text(response.message);
$('#editCategoryModal').modal('hide');
fetchcategory();
}
}
});
});
Controller:
public function update(Request $request, $category_id) {
$validator = Validator::make($request->all(), [
'category_name'=>'required|max:191',
'category_description'=>'required|max:191',
]);
if($validator->fails()) {
return response()->json([
'status'=>400,
'errors'=>$validator->messages(),
]);
} else {
$category_update = HmsBbrCategory::find($category_id);
if ($category_update) {
$category->category_name = $request->input('category_name');
$category->category_description = $request->input('category_description');
$category->update();
return response()->json([
'status'=>200,
'message'=>'Category Edited!',
]);
} else {
return response()->json([
'status'=>404,
'message'=>'Category Not Found',
]);
}
}
}
Things to note:
As you can see, my category_id is being read properly in: url: "/clinical/bbr-category-configuration-update/"+cat_id,. Also, I went ahead and did a console.log to show in my console that the whole table is getting retrieved. My main issue is this 500 internal server error. Not sure if it is by the PUT.
I also tried to change the PUT to POST or GET just to see if there is any change or other errors, but it's still the same 500 internal server issue. PS, my form has csrf.
Your problem is surely $category, you are using $category_update, not $category
when I try to get data in ajax, the returned object is empty
I send the id of the data I want to get in js :
function selectMessage(id) {
$.ajax({
url: '{{ path('back_translation_update') }}',
method: 'GET',
data: {id: id}
}).done(function (response) {
console.log(response)
})
}
$('.updateMessage').click(function (evt) {
evt.stopPropagation()
selectMessage($(this).data('id'))
})
in the controller I look for the data to return :
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request): Response
{
if ($request->isXMLHttpRequest()) {
$id = $request->get('id');
// dd($id);
$message = $this->translationService->getTranslationById($id);
// return new JsonResponse(['data' => $message]);
$response = new Response();
$response->setContent(json_encode([
'data' => $message,
]));
$response->headers->set('Content-Type', 'application/json');
return $response;
}
}
I use a service because with the repository I get an error: getById () must be an instance of Symfony\Component\HttpFoundation\Response
with :
$repositoryMessage = $this->em->getRepository(TranslationMessage::class);
$message = $repositoryMessage->findOneBy(['id' => $id]);
so the service will look in the database:
public function getTranslationById($translation_id)
{
$query = $this->em->createQueryBuilder()
->from(TranslationMessage::class,'message')
->select('message')
->where('message.id = ?1')
->setParameter(1, $translation_id);
$message = $query->getQuery()->getResult();
// dd($message);
return $message;
}
all the dd() give the expected values:
into getById(): the id of the row sought
into getTranslationById(): the sought object
but in the XHR, data contains an empty object: uh:
same with a new JsonResponse, commented here
what did I miss? help
Use Aurowire to get messageRepository object and use $this->json() to return JsonResponse
/**
* #Route("/update", name="back_translation_update", methods="GET|POST")
*/
public function getById(Request $request, TranslationMessageRepository $messageRepository): JsonResponse
{
$id = $request->query->get('id');
$message = $messageRepository->find($id);
if(!$message) { return new NotFoundHttpException(); }
return $this->json([
'success' => true,
'data' => $message
]);
}
Define success function instead of done function
function selectMessage(id) {
$.ajax({
url: "{{ path('back_translation_update') }}",
method: 'GET',
data: { id: id }
success: function(data) {
console.log(data)
}
})
}
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);
}
// ..
});