How do I resend the ajax request from getting TokenMismatchException?
Currently, this is my code.
if ($exception instanceof \Illuminate\Session\TokenMismatchException) {
return redirect()->refresh();
}
This is my ajax request
$.ajax({
url: '/getEventsForRefCode',
type: 'POST',
async: false,
data: {
reference_code: reference_code
},
dataType: 'JSON',
success: function (data) {
}
I didn't pass any token because I already have these
window.Laravel = {!! json_encode([
'csrfToken' => csrf_token(),
]) !!};
$.ajaxSetup({
headers:{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Related
I added this:
<meta name="csrf-token" content="{{ csrf_token() }}">
Its ajax area:
$.ajax({
url: '{{ route('fav.add') }}',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: 'POST',
data: {id},
dataType: 'text',
contentType: false,
processData: false,
success: function(data) {
console.log(data);
}
})
It's my controller:
public function addFav(Request $request) {
return $request->id;
}
I'm not reaching id.
If i change my controller like this:
public function addFav(Request $request) {
return "test";
}
There is no problem, i'm reaching the test text, but when i try to reach id I can not reach. How to fix it? If you help me i will be glad.
I solved this problem. The problem is that 2 rows. I deleted them and it worked fine.
contentType: false,
processData: false,
I'm using ajax to send comments. This is the route
Route::post('/users/add/comment/', 'UsersController#AddComment')->name('AddComment');
The ajax call
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
type: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
and the controller
public function AddComment(Request $request){
dd($request);
}
It always throws that error. I changed the route and the func name a lot of times. but it does the same thing and the dd(); request is always empty.
Thanks in advance!
You have to set the ajax method to post with the attribute 'method', not 'type'.
function SendAny(){
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post',
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
}
I was trying to send the same data using <form> I tried AJAX to have more control over the request.
my form tag goes like <form method="POST" action="/users/add/comment/">
I removed the last / in the URL and it does work. I don't know how or why.
But It works !!!
Form
<form id="YourForm">
...
your inputs
...
</form>
Button
<button type="button" class="btn btn-success SendButton">Save This</button>
JS
<script type="text/javascript">
$(document).on('click', '.SendButton', function (e) {
e.preventDefault();
var data = $("#YourForm").serialize();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
method : "POST",
url : "{{ url('users/add/comment/') }}",
data : data,
dataType : "JSON",
})
.done(function(response) {
alert('Success!');
location.reload();
.fail(function(response) {
console.log("Error: ", response);
});
return false;
});
</script>
You need to change type to method, you use the wrong keyword. Now it is a default GET
$.ajax({
url: '/users/add/comment/',
data: {
"_token": "{{ csrf_token() }}",
"content": 'ksdflsdfnnkn',
},
method: 'post', // it should be method: 'post'
success: function(result) {
if (result == 0) {
location.reload();
} else {
alert("this an ereor")
}
}
});
Button code
this is my button code with id 123
<button type="submit" class="addto" id="123">Add to cart</button>
ajax code
This is my ajax code
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
$id=this.id;
//alert($id);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: '/test', //route url
dataType:"json",
type:"POST",
data:{id:this.id},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});
Route code
this is my route code
Route::match(['get','post'],'/test','ajaxcontrol#test'); //route url
Controller code:
How to solve this, i have included all the imports
class ajaxcontrol extends Controller
{
public function test(Request $request){
$valu=$request->id;
echo json_encode($valu);
}
}
Try to change your ajax like this:
$(document).ready(function(){
$('.addto').click(function (event) {
event.preventDefault();
id=this.id;
//console.log(id);
$.ajax({
url: "{{ url('/test') }}", //route url
dataType:"json",
type:"POST",
data:{
id:id,
"_token": "{{ csrf_token() }}",
},
success: function(result){ //success function
alert("success"); //test alert
}});
});
});
i'm sending the section id in my ajax function,but i can't receive this data in my controller function.need your help please.
This is my jQuery:
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
},
success: function(){
alert(section);
},
error: function(){
alert("error");
}
});
$.post("{{URL::to('/ajax')}} ",function(data){
$('#groupe').empty().html(data);
});
});
});
Web:
Route::post('ajax' , 'SeanceController#ajaxfct');
My function in the controller:
public function ajaxfct(Request $request){
$id = $request->section;
$groupes = \DB::table('groupes')
->where('section_id','=',$id)
->get();
return view('seance.groupe')->with([
'groupes' => $groupes
]);
}
The code is close to working perfectly, the following setup passes the data correctly:
HTML:
<select id="getGroupe">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<script>
$(document).ready(function(){
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#getGroupe').change(function(){
var section = jQuery('#getGroupe').val();
$.ajax({
url: "/ajax",
type: "POST",
data: {
section:section,
}
}).done(function( msg ) {
console.log('response: ', msg)
});
});
});
</script>
Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class SeanceController
{
public function ajaxfct(Request $request)
{
return ['received' => $request->section];
}
}
Route:
Route::post('/ajax', 'SeanceController#ajaxfct');
My second ajax call starts only when the first succeeded. The problem, the second ajax call return 404 error code. Find below the code.
Can anyone help troubleshooting ? Thanks a lot
$.ajax({
contentType: 'application/json',
type: 'GET',
url: '${pageContext.request.contextPath}/transaction/status/'+$("#telephone").val()+'/'+$("#transref").val(),
dataType : 'json',
cache: false,
error: function(xhr,error,textStatus){
console.log(error);
},
success: function(data) {
console.log(data)
if(data.transfertResponseCode == '01'){
$('#statut').empty();$('#statut').append('<div class="row"><div class="col-md-2 col-sm-2"><i class="fa fa-spinner fa-pulse fa-3x fa-fw"></i><span class="sr-only">Loading...</span></div><div class="col-md-10 col-sm-10">Transaction en cours de traitement.... Veuillez patienter quelques instants</div></div>');
}else if(data.transfertResponseCode == '00'){
var data = {"msisdn":$("#telephone").val(), "amount":$("#montant").val(), "transref":$("#transref").val(), "clientid":$("#clientID").val()};
$.ajax({
contentType: 'application/json',
url: 'http://74.208.84.251:8221/QosicBridge/user/deposit',
type: 'POST',
data : JSON.stringify(data),
dataType : 'json',
cache: false,
beforeSend: function (xhr) {
xhr.setRequestHeader("Authorization", 'Basic ' + btoa('USR28' + ":" + 'YG739G5XFVPYYV4ADJVW'));
},
error: function(xhr,error,textStatus){
console.log(error);
},
complete: function(data) {},
success: function (data) {
console.log(data);
}
});
}
}
});