Adding laravel CSRF token with form data - javascript

While uploading an image via wysiwyg editor I need to pass the Laravel CSRF token with the FormData(). But it seems like it fails or it does not add the csrf token using the append() method.
Here is my code:
function uploadImage( image ) {
var data = new FormData();
data.append( "image", image );
data.append( "csrfToken", Laravel.csrfToken ); // <- adding csrf token
// Laravel.csrfToken will return the csrf token.
console.log( data.entries() );
$.ajax ({
data: data,
type: "POST",
url: "/article/store/image",
cache: false,
contentType: false,
processData: false,
success: function(url) {
var image = IMAGE_PATH + url;
$( '#editor' ).summernote( "insertImage", image );
},
error: function( data ) {
console.log( data );
}
});
}
Its not adding the laravel csrf token with the form data because still I am getting an error
TokenMismatchException in VerifyCsrfToken.php line 68
How to add the token with the form data?

You should add a field named - _token, instead of csrfToken like this:
data.append( "_token", Laravel.csrfToken ); // <- adding csrf token
This is what Laravel's helper method - csrf_field() does.
According to Laravel Docs, in case of Ajax calls - you could, for example, store the token in a HTML meta tag::
<meta name="csrf-token" content="{{ csrf_token() }}">
and then include in your ajax header like this:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Hope this helps!

For ajax requests, I like to set it up once with $.ajaxSetup.
In my layout:
<meta name="csrf-token" content="{{ csrf_token() }}">
In my app.js:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
This saves me having to remember to append the _token input to every request.

while #Saumya already answered this question, I use headers to send CSRF tokens like so:
$.ajax ({
data: data,
type: "POST",
headers: {'X-CSRF-TOKEN': Laravel.csrfToken },
url: "/article/store/image",
cache: false,
contentType: false,
processData: false,
success: function(url) {
var image = IMAGE_PATH + url;
$( '#editor' ).summernote( "insertImage", image );
},
error: function( data ) {
console.log( data );
}
});
If you are using ajax to send multiple requests throughout your application, you can set it up globally for every request at once:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': Laravel.csrfToken
}
});
Learn more Here

Related

Ajax: How to send FormData inside of json object

To give you a better understanding consider my ajax request:
$.ajax({
url: '{% url "validate-upload-single" %}',
type: "POST",
data: JSON.stringify({
'mainForm': Myform,
'currentForm': 1,
}),
dataType: 'json', // response type
Where:
var Myform = new FormData( $(this)[0] );
The problem is that when i send the request, i get back an empty 'dict' on the server side. Im using Django as my backend
DJANGO VIEW:
print('SORTING THE POST REQUEST')
body = request.body.decode('utf-8')
serialized = loads(body)
print(f'POST: {request.POST}')
print(f'Body: {body}')
print(f'Serialized: {serialized}')
RESULT:
SORTING THE POST REQUEST
POST: <QueryDict: {'{"mainForm":{},"currentForm":1}': ['']}>
Body: {"mainForm":{},"currentForm":1}
Serialized: {'mainForm': {}, 'currentForm': 1}
I've tried $("form").serializeArray() but this only return text data, files seem to be missing
I guess the problem is with contentType header - it should be 'multipart/form-data'. Check this link to make it work with jQuery.ajax
In the .js file you HAVE TO add the fist block of csrf token for properly working.
//Getting csrf token
var csrftoken = jQuery("[name=csrfmiddlewaretoken]").val();
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Then you use json in you ajax, getting the template that you want to display by variable here "html_form":
// Submit post on submit
$('#post-form').on('submit', function(event){
event.preventDefault();
console.log("form submitted!") // sanity check
//Send data to server for getting back sorted
$.ajax({
url: '/schedule/sort_group/',
async: true,
type: 'post',
data: { //data sent with the post request
group_field_value: $("#select_group").children("#group-option:selected").val(),
lector_field_value: $("#select_lector").children("#lector-option:selected").attr("name"),
},
dataType: 'json',
success: function (data) {
$("#change_by_select").html(data.html_form);
}
});
});
In the views.py file at the bottom you need to determine the data like that:
data['html_form'] = render_to_string('schedule/select_sort.html', context,
request=request)
return JsonResponse(data)
So I suggest the information that you want to retrieve from the server put into the particular another file, whatever it would be (dictionary or lists or other data structures or html templates).
I hope it would help. Feel free to ask any questions.

add new record in CRM using web API

I am trying to add records to CRM using Javascript but getting:
401 Unauthorized Error.
My question is how to get the token and use it inside the JavaScript function.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You need add Authorization information in Http Header. Here is an example if you use JWT.
$(document).ready(function() {
$("#Save").click(function() {
var ProductDetails = new Object();
ProductDetails.ProductName = $("#txt_productName").val();
ProductDetails.ProductDetail = $("#txt_desc").val();
$.ajax({
url: "https://mycrm.dynamics.com/api/data/v9.1/Products",
type: "Post",
headers: {
'Accept':'application/json',
'Content-Type':'application/json',
'Authorization':'Bearer your token here'
},
dataType: 'JSON',
data: ProductDetails,
contentType: 'application/x-www-form-urlencoded',
success: function(data) {
alert('Updated Successfully');
},
error: function(request, status, error) {
alert(request.status);
}
});
});
});
You have to add a header with the bearer token like this:
$.ajax({
(...)
headers: {
"Authorization": "Bearer " + token
},
(...)
In order to get a token you have to register an application in Azure Active Directory first, in the same tenant as your Dynamics 365 instance. Check this link if you need a thorough step by step guide to do it.
After registering you application in AAD you also have to add some code to do the authentication with Azure and getting the token. ADAL.js does this job for you, but keep in mind that it prompts the user to manually add his username and password in a office 365 popup. This is called interactive authentication and as far as I know it can't be avoided.
For a full HTML + JS working example click here.

Laravel error 405(Method Not Allowed) Ajax Posting

Hello i wnat to send my data with ajax to my controller.
My CODE
AJAX
$.ajax( {
type:'POST',
header:{
'X-CSRF-TOKEN':$('meta[name="csrf-token"]').attr('content')
},
url:"{{route('race.post')}}",
data:{
_token: "{{ csrf_token() }}",
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
CONTROLLER
public function Points(Request $request){
$test = $request->input('data');
return "$test";
}
ROUTE
Route::post('updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);
And there are the errors what i get.
Console
Network-preview
Network-Response
I just removed the slash at the end of url and it began working...
/managers/games/id/push/ to:
$http({
method: 'POST',
url: "/managers/games/id/push",
add this one in your layout.blade file
<meta name="csrf-token" content="{{ csrf_token() }}">
then use this one in your js code
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
i hope this will help!!
First thing is we put two routes in one for displaying view and another for post ajax. So simple add both routes in your route file.
routes/web.php
Route::get('ajaxRequest', 'RacesController#Points');
Route::post('ajaxRequest', 'RacesController#Points');
Include this meta tag inside your view
<meta name="csrf-token" content="{{ csrf_token() }}" />
Include javascript code inside your ajax call
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Since you are working in a JavaScript file and not in a Blade file, the route() helper method is not working, and the route 'race.post' isn't parsed to an url.
Try to change the url to this:
url: '/updateC'
When you want to use the route() helper in your JavaScript, you have to add the script to a Blade file, and json_encode the value, you can read more about this in this answer.
I have different way to use it:
AJAX
data = {
selectmanufacturer: selectmanufacturer,
categories: selectCategory,
_token: "{{csrf_token()}}",
productName: productName
};
$.ajax({
url: '{{URL::to('/all-products-data')}}',
type: 'POST',
dataType: 'json',
data: data,
success: function (response) {
},
error: function (response) {
alert(response);
}
});
Controller:
public function Points(Request $request){
$test = $request->all();
return "$test";
}
I hope It will be helpful to you
The URL you’re posting to doesn’t look right in the console output you posted. In your AJAX code, you have this:
url:"{{route('race.post')}}"
But that’s just getting interpreted as is, it’s not getting interpreted as the value of that route in Laravel.
You’ll need to make sure that your JavaScript code is in a Blade template if you want Blade tags parsed.
not type: "POST", method :'POST" try the below code i have modified. ref: Reference Link
HTML code
<button onClick="onBtnClick()" data-url="{{route('race.post')}}"></button>
Updated Code
function onBtnClick(){
var token = $('meta[name="csrf-token"]').attr('content');
var url = $(this).attr("data-url");
$.ajax( {
method:'POST',
header:{
'X-CSRF-TOKEN': token
},
url: url,
data:{
_token: token,
dataType: 'json',
contentType:'application/json',
}
})
.done(function() {
alert('success');
})
.fail(function() {
alert("error");
});
}
Check if your laravel route is correctly set for this request.
In my case, I had a $.ajax url: "crop-image-upload" and a Route::post('crop-image-upload ', 'CropImageController#uploadCropImage');
But the request was sent to http://127.0.0.1:8000/news/crop-image-upload
So I had to change my route to Route::post('/news/crop-image-upload ', 'CropImageController#uploadCropImage');
So, in your case, try to add a literal url on ajax like this:
url:"/races/updateC"
and add 'races/' in the route like this:
Route::post('/races/updateC', ['uses' =>'RacesController#Points', 'as' => 'race.post']);

Ajax request to laravel backend results in 404

I never made an ajax request using laravel so it's different than just plain php.
This is my script that is attached on a dropdown onchange:
function createcomploadtemplate(){
var ifprefix = $("#createcomploadtemplatedropdown").find("option:selected").text();
var getidtemplate = $('#createcomploadtemplatedropdown').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: 'ajaxfixedcompany',
data: {getidtemplate:getidtemplate,ifprefix:ifprefix},
dataType: 'json',
encode : true,
success: function(data){
alert(data.success);
}
});
}
This is my route
Route::post('ajaxfixedcompany',['middleware' => 'auth', 'as' => 'ajaxfixedcompany', 'uses' => 'AjaxController#ajaxfixedcompany']);
And this is the function
public function ajaxfixedcompanyget(Request $request){
$response = array(
'status' => 'success',
'msg' => $request->message,
);
return response()->json($response);
}
If i use ajax url /ajaxfixedcompany instead of ajaxfixedcompany in chrome devtools i get "The page doesnt exist" with error 404
And without the / i get this:
EDIT: OMG...I think i just needed a break from all this. I have 2 controllers. 1 for POST and 1 for GET. i am requesting a POST while in my controller i only have my GET function created... It works again. lmfao
you can do this with csrf token.
$.ajax({
type: "POST",
url: "url/update",
dataType: 'json',
data: 'id=' + id+ '&_token={{csrf_token()}}',
Hope it helps.
Well i just needed a break. After that 1hour break i came back and noticed that i am making a post request, while it is also called in my route, but i had a typo in my controller....silly me... lmfao

Ajax Post to Laravel - CSRF Token Mismatch

I am trying to post data to Laravel backend with ajax, however I am getting 'CSRF token mismatch' error.
First, I've placed token in html (in body but outside its form because it's not the whole form, its only 2 elements to be posted):
<input type="hidden" name="_token" id="token" value="{{ csrf_token() }}">
Then in 'document ready', I try to post the data with ajax.
data["_token"] = jQuery('#token').val();
// Also tried this:
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': jQuery('#token').val()
}
})
console.log(data) // returns the array with _token: "esOKmY8Tpr4UvhTYMhWcWui0rpvYEjJ3es7ggics"
jQuery.ajax({
type: "POST",
url: '/my-route',
data: data,
success: function() {
console.log("A");
}
});
The data which I want to post are little chunk of a bigger form, and with using this approach, I can autocomplete form. The little chunk of html inputs are not inside any other sub-form. Maybe this can be the case?
- Form:
- A: bla // to be posted
- B: hello // to be posted
- C: smt else // no post
but getting the values are working okay
Route:
Route::post('/my-route', 'AdminController#theFunction')->middleware('admin');
Edit: I changed <input> to <meta> tag
I had the same problem
try to put include CSRF tag in your meta like so
<meta name="csrf-token" content="{{ csrf_token() }}" />
and read it in your ajax code like so :
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
Last Update
Please modify your url variable like so :
jQuery.ajax({
type: "POST",
url: '/my-route'+'?_token=' + '{{ csrf_token() }}',
data: data,
success: function() {
console.log("A");
}
});
Try This
var formData = new FormData();
formData.append("_token", "{{ csrf_token() }}");
$.ajax({
headers: {
'X-CSRF-TOKEN': "{{ csrf_token() }}"
},
url: 'save_search',
data: formData,
processData: false,
type: 'POST',
success: function ( data ) {
alert( data );
}
});

Categories

Resources