CSRF token not working in a Laravel ajax call - laravel

I've checked the gizillion answers to this question and for some reason I can't get this to work.
I get the error:
401 (Unauthorized)
My route is an api route guarded.
My data:
let ajaxMainTemplate = {
'mainTemplate': mainTemplate,
'templateId': templateId,
'_token': accessToken,
}
My ajax call:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
data: {
_token: ajaxData._token,
ajaxData
},
success: function(response) {
console.log(response)
}
})
I've tried the above to test based on another response. I put the token outside of the ajaxData object. I get the same error. I've also attempted:
$.ajax({
type: 'POST',
url:`../api/aiMainTemplate/${ajaxData.templateId}`,
headers: { 'X-CSRF-TOKEN': ajaxData._token },
data: ajaxData,
success: function(response) {
console.log(response)
}
})
Same.
I've also confirmed the token is there by adding a console.log Any ideas what I'm doing wrong with this?

My url was behind the api protected route so I had to do an ajax call to login into it via ajax.
The credentials are in a variable ajaxData.
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8000/api/login',
data: ajaxData,
success: function(response) {
shopifyToken = response.success.token;
getListProducts(shopifyToken);
}
});
With the shopify token generated from this login it worked.

Related

Add bearer token to ajax POST request in ASP.Net Core

I have a POST method /Home/PostRequest decorated with the [Authorize] attribute in ASP.Net Core. Client-side I have an authenticated user. I want to construct an ajax POST request to call the method, but I'm unsure what to put into the Authorization header. Where are the auth credentials cached, and in what form?
$.ajax({
type: "POST",
url: "/Home/PostRequest",
data: JSON.stringify(request),
headers: {
"Authorization": "** what to put here? **"
}
contentType: "application/json",
dataType: "json",
crossDomain: false,
success: function (response) {
successCallback(response);
},
failure: function (response) {
console.log("Failed");
},
error: function (xhr, response, thrownError) {
console.log("Error");
}
});

ASP.NET Core FromBody is null on AJAX POST but populates in Postman

I'm trying to perform an AJAX post but I keep getting a null FromBody in my .NET controller. I think it has to do with how I'm formatting my AJAX post.
When I attempt to post with AJAX I get a null FromBody.
var data = {
Date: "2016-12-01",
BurnIdx: 23,
BurnStatIdx1: 3,
BurnStatIdx2: 3,
BurnStatIdx3: 3,
BurnSevIdx: 5,
WorkOrder: 32426,
Comment: "Hi"
};
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (result) {
console.log('Data received');
console.log(result);
}
});
});
However, when I attempt a post in Postman it's successful.
Figured out my problem. Needed to use JSON.stringify on my data.
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
console.log('Data received');
console.log(result);
}
});
Not only the JSON.stringify().
If your data don't match with csharp class data it doesn't receive anything.
Like if you define in the class a field with int type, and send it in the json like "1", it happens to receive the whole data as null
I know you are already figured out of this problem. But I faced with the same just right now. My mistake was I used BODY parameter instead DATA in ajax request.
My Invalid ajax:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
body: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
Valid:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
data: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
}

Laravel - DELETE Ajax request

I am using Laravel 5.0. I have created a RESTful Controller. Now i wanna use the destroy function via an ajax call.
This is my JS:
$.ajax({
type: 'POST',
url: '/pv/' + data.id,
data: {_method: 'delete' },
success: function(data){
console.log(data);
}
});
And this is my destroy function:
public function destroy($id)
{
$pv = PV::find($id);
$pv->delete();
return true;
}
All i got is a 500 error.
first check your route in laravel
Route::delete('/deleteprocess', 'Controller#destroy');
in javascript
$.ajax({
url: '/deleteprocess',
type: 'POST',
data:{
'_token': $('meta[name=csrf-token]').attr("content"),
'_method': 'DELETE',
},
success: function(result) {
// Do something with the result
}});
set type : POST,
set token : _token,
set method : _method as DELETE,
That's probabily a "CSRF" Exception. If you are using Ajax Request with jQuery, add this (before your $.ajax):
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
And, in your "html" ..create a new "meta tag" with csrf-token..value:
{{ csrf_token() }}
Read more: http://laravel.com/docs/5.0/routing#csrf-protection

jQuery Ajax POST Failing

I can't get my AJAX request to complete successfully. It's for the bearere token on Twitter's API. I have done successfully in a HTTP request client as shown below:
But I can't replicate this in code:
$.ajax({
type: 'POST',
url: 'https://api.twitter.com/oauth2/token',
headers: {
'Authorization':'Basic ' + base64EncodedBearerTokenCredentials,
},
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
data: {
'grant_type': 'client_credentials'
},
error: function(xhr, status, error) {
},
success: function(response){
},
});
I'm getting a 405, but because I have the Authorization header in I can't see the response in Firebug.
What is it?
Thanks.

Ajax Success Function not working

I am using Ajax to add contents on my database. And here's the code:
function addToFavorites(){
var recipe_id = $("#recipe_id").val();
var url = connect_url+'addFavorite.php?user_id='+user_id+'&recipe_id='+recipe_id;
$.ajax({
type: 'POST',
data: [{
user_id: user_id,
recipe_id: recipe_id
}],
url: url,
async: true,
jsonpCallback: 'userCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
alert("HELLO!!!");
},
error: function (e) {
alert("ERROR!");
}
});
}
The Ajax call was successful and I was able to add records on the database but I'm just wondering why is it not displaying the alert message if the calling was successful? Is there something wrong with my code? Or is there something wrong with my understanding? Thanks!
you must give a response with some info to the ajax or it won't know the response succeeded

Resources