Good I am trying to delete through ajax but I get the following error:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
I searched the error and apparently appears by the token so I have done what they recommended, I added in the view this:
<meta name="csrf-token" content="{{ csrf_token() }}">
ajax:
$('#delete').on('click', function(){
var x = $(this);
var delete_url = x.attr('data-href')+'/'+x.attr('data-id');
$.ajax({
url: delete_url,
type:'DELETE',
headers:{
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr('content')
},
success:function(result){
alert('success');
},
error:function(result){
alert('error');
}
});
});
controller:
public function destroy($id)
{
$appointment = Appointment::find($id);
if(appointment == null) {
return Response()->json([
'message'=>'error delete.'
]);
}
$appointment->delete();
return Response()->json([
'message'=>'sucess delete.'
]);
}
route:
Route::name('appointments.destroy')->delete('/citas/{id}', 'AppointmentController#destroy');
it is certainly a token error because if I do not need it on the route it does it perfectly ...
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'citas/*'
];
}
You can check the exact error on developers console, network tab. Look there for your request and check the preview or open it in a new chrome's tab.
Posted code has a typo, maybe it is in your file too? You missed to add $ to your appointment variable.
public function destroy($id)
{
$appointment = Appointment::find($id);
if($appointment == null) {
return Response()->json([
'message'=>'error delete.'
]);
}
$appointment->delete();
return Response()->json([
'message'=>'sucess delete.'
]);
}
Related
Using a simple Ajax GET request to retrieve some data, it successfully checks if($request->ajax()) {} but then fails any validation because there is no data in the Request $request variable. This happens only on the production server, on localhost everything works fine.
The console shows the intended URL https://example.com/employeeInfo?id=1, then error 422 (Unprocessable Entity). Output from error: function(jqxhr, status, exception) { alert('Exception:', exception); } gives an empty alert message.
View
<script>
(function ($) {
$(document).ready(function() {
$(".team-pic").off("click").on("click", function() {
$id = $(this).data('id');
// Get data
$.ajax({
type: 'GET',
url: 'employeeInfo',
data: {'id':$id},
success: function(data){
var obj=$.parseJSON(data);
// Show output...
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
});
});
}(jQuery));
</script>
Route
Route::get('/employeeInfo', 'EmployeeController#get');
Controller
public function get(Request $request) {
if($request->ajax()) {
$this->validate($request, [
'id' => 'required|integer',
]);
// Id
$employee = Employee::find(request('id'));
// Create output
$data = ...
echo json_encode($data);
}
}
If I were you, I would use a RESTful API with route model binding, specifically the explicit binding.
RouteServiceProvider.php
public function boot()
{
parent::boot();
Route::model('employee', App\Employee::class);
}
Route
Route::get('api/employees/{employee}', 'EmployeeController#get');
Controller
public function get(Employee $employee)
{
// The id being valid is already done by forcing it to be an Employee
// It is also an ajax call because it is going to the api route
// This will json_encode the employee object.
return $employee;
}
I have a problem following this tutorial to implement a simple chat in Laravel using Pusher and Vue.js: Link tutorial.
My app.js file in assets/js where I make the request is this one:
const app = new Vue({
el: '#app',
data: {
tweets: []
},
created() {
this.showTweets();
Echo.private('chat')
.listen('TweetSentEvent', (e) => {
this.tweets.push({
tweet: e.tweet.tweet,
user: e.user
});
});
},
methods: {
showTweets() {
axios.get('/tweets').then(response => {
this.tweets = response.data;
});
},
addTweet(tweet) {
this.tweets.push(tweet);
axios.post('tweets', tweet).then(response => {
console.log(response.data);
});
}
}
});
My web.php routes:
Auth::routes();
Route::get('/', 'TweetController#index');
Route::get('tweets', 'TweetController#showTweets')-
>middleware('auth');
Route::post('tweets', 'TweetController#sentTweet
My controller is this one:
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
return view('chat');
}
public function showTweets(){
return Tweet::with('user')->get();
}
public function sendTweet(Request $request){
$user = Auth::user();
$tweet = $user->tweets()->create([
'tweet' => $request->input('tweet')
]);
broadcast(new TweetSentEvent($user, $tweet))->toOthers();
//return ['status' => 'Tweet Sent!'];
}
When I'm running the app and I try to send a tweet through a POST request clicking on my send button, this error apperas on the console:
POST http://localhost/youChat/public/tweets 500 (Internal Server Error)
Uncaught (in promise) Error: Request failed with status code 500
at createError (app.js:13931)
at settle (app.js:35401)
at XMLHttpRequest.handleLoad (app.js:13805)
Everything seems to be fine... Any help? Thanks in advance!!
I get TokenMismatchException when using nested AJAX calls. The first AJAX call works fine but the second always goes to error instead of success.
What I'm trying to do is that when the user registers from the button in the nav bar I want him to go to the dashboard or /home - this works okay. But, when the user fills the form (to buy something) on the index page, I want him to:
Have his input checked for validity, then, check if he's logged in, if not then the registration modal pops up. After he's registered I want him to be redirected to the checkout page.
However, what happens is that when the user fills the buying form and hits submit, the first ajax checks if the input in the buying form is valid, if it is, then check if he's logged in if not return 401 error.
401 gets picked up by the first ajax and directs the flow to 401 handling where the registration modal pops up to register, that's when the 2nd ajax pop up. After he's registered the back-end keeps returning 500 because of CSRF token mismatch.
First, this is the nested ajax:
<script type="text/javascript">
$(document).ready(function(){
$('#topup-form').submit(function(e){
e.preventDefault();
var topup_info = $('form').serialize();
//FIRST AJAX
$.ajax({
url: $('form').attr('action'),
method: 'post',
data: topup_info,
type: 'json',
//if success show success message for user
success: function(result){
alert(result.responseJSON.code);
$('.alert.error').slideUp(200);
$('.alert.success').append("<p class='lead'>Thanks! To checkout we go!</p>").slideDown(200);
},
//for error check if it's 400 (validation) or 401(authentication)
error: function(errorData){
// alert(errorData.responseJSON.code);
if(errorData.responseJSON.code === 400){
var error = errorData.responseJSON.message;
$('.alert.error').text('');
$('.alert.success').slideUp(200);
for (var i in error){
for (var j in error[i]) {
var message = error[i][j];
$('.alert.error').append("<p class='lead'>" + message + "<p>");
}
}
$('.alert.error').slideDown(00);
}//end error 400
//for authentication failure, show registeration modal
else if (errorData.responseJSON.code === 401) {
//change somethings in registeration modal
$('#myModalLabel').html('Please Login First');
$('#register').trigger('click');
document.getElementById('formRegister').action = "{{ route('user.regtopup') }}";
//when registeration form is submitted..
$('#formRegister').submit(function(e){
e.preventDefault();
//fire 2nd ajax
$.ajax({
url: $('#formRegister').attr('action'),
method: 'post',
data: $('form').serialize(),
type: 'json',
success: function(result){
alert('success!!!');
},
//it keeps going to error! complaining about csrf token mismatch
error: function(result){
console.log(JSON.stringify(result));
},
})//end of 2nd ajax
});//end of 2nd submit
}//end of 401
}//end of error
});//end of first ajax
});//end of first submit
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
})
});
</script>
Second, this is the controller that checks input validity and return 401 when not registered:
public function etiPost(Request $request) {
$validator = [
'topupAmount'=> 'required|integer|between:10,500',
'phonenumber'=> 'required|regex:/^05[602][0-9]{7}$/',
];
$inputs = $request->all();
Log::info($inputs);
$validator = Validator::make($inputs, $validator);
if($validator->fails()){
return Response::json([
'error' => true,
'message' => $validator->messages(),
'code' => 400
], 400);
}
elseif (Auth::check()) {
return view('pages.checkout', compact('inputs'));
}
else {
return Response::json([
'error' => true,
'message' => "Please login first",
'code' => 401
], 401);
}
}
This is the overloaded register method that returns JSON when registration is successful. Here is where 500 is returned! When I Log the returned JSON it comes out as normal 200 response but it arrives at the "Whoops" 500 error to the 2nd ajax! The user is registered successfully in the database but this method returns 500 which is caught by the error part of the ajax call.
/**
* Handle a registration request for the application (overloaded).
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = $this->validator($request->all());
if ($validator->fails()) {
$this->throwValidationException(
$request, $validator
);
}
$this->guard()->login($this->create($request->all()));
// return response()->json();
return response()->json(['msg' => 'Success! You have been registered!'], 200);
}
I won't include the forms for brevity but rest assured I added all the CSRF input tags and the meta tag in the head of the HTML.
What should I do differently to avoid this? The first ajax works but the second doesn't.
Set header token for each ajax call
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
Also note that you have to add mete token in your template
you can add meta token like this in template
<meta name="csrf-token" content="{{ csrf_token() }}">
if you still want to disable csrf token then
Excluding URIs From CSRF Protection
Sometimes you may wish to exclude a set of URIs from CSRF protection. For example, if you are using Stripe to process payments and are utilizing their webhook system, you will need to exclude your Stripe webhook handler route from CSRF protection since Stripe will not know what CSRF token to send to your routes.
Typically, you should place these kinds of routes outside of the web middleware group that the RouteServiceProvider applies to all routes in the routes/web.php file. However, you may also exclude the routes by adding their URIs to the $except property of the VerifyCsrfToken middleware:
<?php
namespace App\Http\Middleware;
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;
class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
'stripe/*',
];
}
Instead of 'stripe/*', if you give '/*' then it will disable token for all
For more detail :
https://laravel.com/docs/5.5/csrf#csrf-x-csrf-token
please follow code in your jquery before ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
it's not advisable to add CSRF token in meta because all pages are not contain form to submit value so use this solution so you can use CSRF only for your js perspective.
Thank you
I am upgrading my laravel 4 app to laravel 5.2 and there are so many things which I have to reconsider in my codes. One of this is the CSRF thing for AJAX requests. I can't figure out how to handle it properly in my routes file.
Of course, I have include the meta for csrf in my view:
<meta name="csrf-token" content="{{ csrf_token() }}" />
my routes file:
Route::post('/edituser', 'UsersController#toEditUser');
my script:
var _token = $('meta[name="csrf-token"]').attr('content');
function triggerEditUser(id){
$.post(_token+'/edituser',{id:id},function(data){
if(data){
console.log(data);
}
});
}
my controller:
public function toEditUser(){
if(Request::ajax()){
$user = User::find(Input::get('id'));
return Response::json($user);
}
}
I'm getting the error message:
http://mysite.local/kg9VLUc0QWP59AqSP0OCPWjwsWPg33ypZ47FecRC/edituser 404 (Not Found)
As given Laravel documentation, you should use the headers to send the csrf token.
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
,
$.post('/edituser',{id:id,_token:_token},function(data){
if(data){
console.log(data);
}
});
Alternatively, you can also send the token as the data
May be your solution would be something like
$.post( '/edituser',{id:id, token:_token},function(data){
in place of
$.post(_token+'/edituser',{id:id},function(data){
just to test and tell me the answer.
in your controller change
public function toEditUser(){
if(Request::ajax()){
$user = User::find(Input::get('id'));
return Response::json($user);
}
}
by
public function toEditUser(){
if(Request::ajax()){
$user = User::find(Input::get('id'));
foreach ($user as $u) {
$users[]=$result->yourcolumn;
}
return $users;
}
}
and add
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
I am making an app in ionic and the backend is made in Laravel. I am working on a password reset functionality, and I keep getting the above mentioned error, when I am testing endpoints in chrome. This is the code for the contact information function:
sendContactConfirmation: function(contact, reset) {
var defer = $q.defer();
if(reset == 'reset'){
var endpointUrl = $http.post(AppSettings.apiUrl + "/users/reset", { phone: contact });
}
else {
var endpointUrl = $http.post(AppSettings.apiUrl + "/users", { phone: contact });
}
endpointUrl.then(function(result) {
service.set(result.data.user);
defer.resolve(result);
}, function(error) {
defer.reject(error);
});
return defer.promise;
},
And these are the routes in my Laravel back-end:
Route::group(['jwt.auth', ['except' => ['authenticate']], 'prefix' => 'api', 'namespace' => 'Api'], function() {
Route::post('authenticate', 'AuthenticateController#authenticate');
Route::get('authenticate/user', 'AuthenticateController#getAuthenticatedUser');
Route::post('users', 'UsersController#register');
Route::post('users/reset', 'UsersController#resetContact');
Route::put('users/{user}/reset', 'UsersController#resetPassword');
Route::put('users/{user}', 'UsersController#update');
Route::put('users/{user}/activate', 'UsersController#activate');
Route::post('users/{user}/pic', 'UsersController#uploadPicture');
});
And this is the resetContact function:
public function resetContact(Request $request)
{
$this->validate(
$request,
['phone' => 'required|regex:/^[0-9]{8}$/']
);
$user = User::where('phone', $request->get('phone'))->firstOrFail();
if ($user) {
try {
$this->sendValidationCode($user, 'reset');
}
catch (\Exception $e) {
throw new ApiException($e->getMessage(), 500);
}
}
return response()->json([
'user' => $user,
]);
}
Not sure why do I get this 400 Bad request error for this.
When using Laravel JWT make sure you always send the token for all routes under jwt.auth otherwise you will get the error 400 = Token not provided. In ionic make sure your toke is provided on each call to your laravel endpoint to avoid this error.