TokenMismatchException in VerifyCsrfToken.php line 53 - ajax

i made a page view/maessage.php
https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js">
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:{'_token': '{{ csrf_token() }}'},
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
in routes.php
Route::get('/ajax',function(){
return view('message');
});
Route::post('/getmsg','AjaxController#index');
in AjaxController.php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
class AjaxController extends Controller
{
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
}
when i ran http://localhost:8000/ajax
http://localhost:8000/getmsg generate below error
Whoops, looks like something went wrong.
1/1 MethodNotAllowedHttpException in RouteCollection.php line 218: in
RouteCollection.php line 218 and buch of error.....
but when i saw in consol it show below error
TokenMismatchException in VerifyCsrfToken.php line 53: in
VerifyCsrfToken.php line 53
i can't understand error .i am fresher in laravel. and i aactually don't know the meaning of '_token': '{{ csrf_token() }}' in message.php. pls. help to solve this error.

This exception:
MethodNotAllowedHttpException
is telling you that the method on your form is not the same as the method on your route.
So you have 2 options to solve this issue.
First option : Change route method type
Your route has a GET
Route::get('/ajax',function(){
return view('message');
});
but your form has a POST
so change it to:
Route::post('/ajax',function(){
return view('message');
});
Second option: change your ajax-form method type
Route::get('/ajax',function(){
return view('message');
});
<script>
function getMessage(){
$.ajax({
type:'GET',
url:'/getmsg',
data:{'_token': '{{ csrf_token() }}'},
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
Regarding your question about CSRF . It protects against Cross Site forgery. You can read about it here: https://laravel.com/docs/5.4/csrf

Related

How to Show Flash Message after adding / Deleting Data using Ajax in Laravel; 8

Need help for Showing Flash Message after adding / Deleting Data using Ajax in Laravel 8
i included the file "flash-message.blade.php"
<div class="content-wrapper">
#include('flash-message')
My Controller File
public function deleteData(Request $req)
{
$deletedata = buffalodata::destroy($req->id);
return response()->json( $deletedata );
}
Ajax Call for Delete Data
$(document).on('click', '#footer_delete_button', function() {
$.ajax({
type:'post',
url: '/deleteData',
data:{
'_token': $('input[name=_token]').val(),
'id' : $('.did').text()
},
success: function(data) {
console.log("Success");
$('.item' + $('.did').text()).remove();
location.reload()
}
});
});
Thanks in Advance....
You can use https://github.com/stanlemon/jGrowl after deleting successfully
I have used this as shown below:
Add this script in your layout.blade.php file
function popUpMessage(colorTheme, message) {
$.jGrowl(message,
{
theme: colorTheme
}
);
}
For success call this:
popUpMessage('bg-success', "Deleted successfully");
For error call this:
popUpMessage('bg-danger', "Some error occured");
'bg-success' and 'bg-danger' are bootstrap classes, you can use your own
If you want to flash session messages from controller then you can use:
Add this to your flash-message.blade.php
#if (session()->has('success'))
<script>
popUpMessage('bg-success', "{{ session()->get('success') }}" );
</script>
#elseif (session()->has('error'))
<script>
popUpMessage('bg-danger', "{{ session()->get('error') }}");
</script>
#endif
Then after successfully deleting you can call this form controller:
session()->flash('success', 'Deleted Successfully');
For error
session()->flash('error', 'Some error occurred');
As you are using ajax then don't use location.reload()

Laravel controller not responding back on AJAX request

i am typing text in text area
<input placeholder="DISCOUNT COUPON" type="text" id="coupon">
Sending that text to controller using ajax;
$.ajax({
type: "POST",
url: "applyCoupon",
data:{
coupon: $('#coupon').val(),
course_id: {{$course->id}},
_token: {{ csrf_token() }},
},
success: function(dataResult){
alert("success");} // why i am not GETTING this alert?
Controller:
public function applyCoupon(Request $request)
{
$result=new \stdClass();
$coupons = Coupons::select('discount_percentage')->where('coupon_code',$request->get('coupon'))
->where('course_id',$request->get('course_id'))
->get();
$course = Course::findOrFail($request->get('course_id'));
$discounted_price= ($course->price) - (($course->price)*($coupons[0]->discount_percentage)/100);
$result->val = $discounted_price;
$result->statusCode = 200;
return json_encode($result);
}
Web.php:
Route::post('course/applyCoupon', ['uses' => 'CoursesController#applyCoupon', 'as' => 'courses.applyCoupon']);
everything seems fine, but why success function is not running?
You should be using routes/api.php instead of routes/web.phpin the first place.
Also, log error by adding
...
error: function (request, error) {
console.log(error);
alert("Error");
},
That should give you a clue. Could be anything depending on your setup.
You're not using the full URL you setup in your routes/web.php
Change
url: "applyCoupon",
to
url: "course/applyCoupon",
or even better would be to use the route name you provided
url: "{{route('courses.applyCoupon')}}",
Give correct route to your ajax call
Pass this in your ajax url.
url: "{{ route('courses.applyCoupon' }}"
if still not working, then Check your network tab in inspect tool
Click on the ajax call and it will show you the detail on your right side.
post here what you are getting there.
You need to give the response in return of ajax call:-
use Response;
return response()->json(['message' => 'error', 'data' => $data]);

Send data per Ajax to Controller in Laravel 5.8

I have the Ajax request
Here is the code of script
<script>
$('#variant_model').change(function(){
var value = $('select#variant_model').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type:"POST",
url: "showVariantModel",
data: value,
success: function(data){
alert(data);
}
})
});
</script>
When I put in my web.php the code
Route::post('/showVariantModel', function(){
if(Request::ajax()){
return var_dump(Response::json(Request::all()));
}
});
Everything looks fine and I receive the response in my alert.
But when I want to put everything into controller I receive the error 500 in the console
Below I will add my code from my web.php and Controller.
Framework is Laravel 5.8
//web.php
Route::post('/showVariantModel', 'VariantsController#checkAttribute');
//VariantsController.php
public function checkAttribute()
{
if(Request::ajax()){
return var_dump(Response::json(Request::all()));
}
Who knows what am I doing incorrect, please give an advice...
Updating the error
https://i.stack.imgur.com/iDvvG.jpg
Thank's Md.Sukel Ali I updated my controller. Not it looks
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Variants;
class VariantsController extends Controller
{
public function checkAttribute(Request $request)
{
if($request->ajax()){
return response()->json($request->all());
}
}
}
Everything works fine now.
Thank you.
The closing tag is missing
public function checkAttribute()
{
if(Request::ajax()){
return Response::json(Request::all());
}
}
Instead of blinding guess what happening under the hood of ajax call. I suggest you to learn how to debug ajax request.
Go to your browser right click and Inspect then go to Network tab then you can see your request. Click on your request then look for response tab. There you can find exactly what happened.
public function checkAttribute(Request $request)
{
if($request->ajax())
{
return response()->json($request->all());
}
}
You need to add imports in your controller:
use Illuminate/Http/Request;
use Illuminate/Http/Response;

Admin ajax in wordpress is not working

I am using admin ajax but it is not working. Kindly, help me to find out the problem. Here is jquery code
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit(){
var newPostsForm = jQuery(this).serialize();
jQuery.ajax({
type:"POST",
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
return false;
}
}):
If I alert the var "newPostsForm" , it shown the posted values.but it is now proceeding to ajax. Here is the from I am using
<form type="post" action="" id="newPostsForm">
<input type="hidden" name="action" value="addPosts"/>
<!-- input fields -->
</form>
An here is the WordPress function I am using. this function is another file. HTML and javascript are in same file
function addPosts(){
echo "<pre>";
print_r($_POST);
die();
}
add_action('wp_ajax_addPosts', 'addPosts');
add_action('wp_ajax_nopriv_addPosts', 'addPosts'); // not really needed
Check to see if the script is getting processed by PHP before it is sent to the client. Change the code to something similar to this:
jQuery(document).ready(function($) {
jQuery('#newPostsForm').submit(ajaxSubmit);
function ajaxSubmit() {
var newPostsForm = jQuery(this).serialize();
var url = "<?php echo admin_url('admin-ajax.php'); ?>";
alert("Submitting to URL: " + url);
jQuery.ajax({
type:"POST",
url: url,
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
},
error: function (xhr, status, err) {
alert("Got status " + status + " and error: " + err);
}
});
return false;
}
});
If you get an actual URL like https://mysite.example.org then check that the URL goes to a valid location. If you get <?php echo admin_url('admin-ajax.php'); ?> then your code is not getting processed by PHP, and the AJAX call will fail because you are not using a valid URL.
The problem seems that the AJAX URL is not accessible in JS code. If the JS code written into a PHP page then only the code will work. Because the PHP code cant be executed into the JS files.
NOW the solution is to localized the JS file. Please follow the code.
wp_localize_script( 'handle', 'settings', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
Write the above code just under where you have enqueued your js file.
NOW in JS file :
jQuery.ajax({
type:"POST",
**url: settings.ajaxurl,**
data: newPostsForm,
success:function(data){
jQuery("#feedback").html(data);
}
});
Hope it will work at your choice.

TokenMismatchException Laravel 5 & BackboneJs

I am developing a Laravel 5-BackboneJs Application. I'm using RESTful Resource controllers to make my own api.
I've got a Backbone model then I am calling save model method. It makes an ajax request like this:
gerencia.app/es/customrole/1
That's why I am trying tu update the model with id 1.
Backbone creates a request with PUT method:
But it gives me 500 internal server error! I see the preview then:
This is a TokenMismatchException from Laravel, then I've found I've got to send a token so I did this in my blade view:
<meta name="token" content="{{ Session::token() }}">
Then I've create a function to set the token and add this function to ajax beforeSend method:
function sendAuth( request ){
console.log( request );
return request.setRequestHeader("X-CSRF-Token", $("meta[name='token']").attr('content'));
}
model.save({
beforeSend: sendAuth,
success: function(){
console.log( 'success!' );
},
error: function(){
console.log( 'error!' );
}
});
But it doesn't work in spite of I see the token in request headers :(
Any help?
I was able to get this working by following the instructions on the Laravel site. I added this to my global layout file:
<meta name="csrf-token" content="{{ csrf_token() }}" />
Then, I created a JS file called csrf-token.js, and placed this code in it:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
After doing that, the POST requests from Backbone worked correctly and I can see the extra header in the request. The key for me was to include the csrf-token.js file AFTER Backbone:
<script src="{{ asset('js/lib/backbone-min.js') }}"></script>
<script src="{{ asset('js/csrf-token.js') }}"></script>
I guess Backbone overwrites the ajax setup options when it loads, so you need to include your changes after that.
My solution is to add a new key/value called token in my model method:
model.save({
"_token" : $("meta[name='token']").attr('content'),
success: function(){
console.log( 'success!' );
},
error: function(){
console.log( 'error!' );
}
});
You can post another solution to this issue.

Resources