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 );
}
});
Related
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']);
I need to pass two different datas using ajax.
I've got this:
$('#sendcover').on('click',function(){
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: new FormData($('#test')[0]),
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
<form name="test" id="test" method="post" enctype="multipart/form-data">
<input type="text" value="{{article.id}}" name="id" />
<input type="file" name="cover">
<button id="sendcover" type="submit" class="saveData">Save</button>
</form>
I need to pass two var's with data:
id and cover
id - sends {{article.id}}
cover - sends image
(and on the backend side it's uploading img and converting it - but it's already done by someone else)
Could somebody help me how to do it properly? I've never did such thing, and I can't find any working answer. :(
You could send it as an splitted up object like
data: {
myId: id,
myCover: cover
}
but currently you send the whole form that actually should look like
$('form#test').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: "POST",
url: "{{ url('articles_changecover') }}",
data: formData
processData: false,
contentType: false,
success: function (data) {
alert(data);
}
});
});
And viewing the source looks fine to send...at least for me ^^
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
I am sending data via ajax to my controller as
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
contentType: "application/json; charset=utf-8"/*,
success:function(id){
alert(sessionStorage.getItem('user_id'));
}*/
});
and in the controller I am using
public function getUserMessages(){
$id = Input::get('id');
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
echo "id is ",$id;
return $messages;
}
I am getting nothing in $id. I have also tried $_POST['id'] which says undefined index id. How I can retrive the id value?
$request->has('id') returns false too.
You should use the Request class instead of Input:
public function getUserMessages(\Illuminate\Http\Request $request){
$id = $request->id;
$messages = Message::where('message_by' , Auth::user()->id)->where('message_for',$id)->get();
return $messages;
}
Your ajax call doesn't work and will throw a 500 Server Error because you need to pass laravel's csrf token with it whenever you POST something. Create a meta tag at the top of your blade view like:
<meta name="_token_" content="{{ csrf_token() }}">
and get the value when you are doing the ajax call:
$.ajax({
url: '/test',
type: 'POST',
data: {
id: sessionStorage.getItem('user_id'),
_token:document.getElementsByName('_token_')[0].getAttribute('content')
},
success:function(id){
alert(id);
}
});
Most likely the success function in your ajax call will only alert [object Object], to get a better overview over whats returned, use
console.log(id);
instead.
You may also create an error function for the ajax call so that possible errors will be shown. Just do add
error: function(err){
console.log(err);
}
after the success function.
The problem is that you are setting the application content as json, You don't need to set the content.
jQuery ajax
contentType (default: 'application/x-www-form-urlencoded; charset=UTF-8')
$.ajax({
url: 'test',
type: 'POST',
data: { id: sessionStorage.getItem('user_id') },
dataType: 'json',
success:function(data){
console.log(data); // always good to output content for debugginn
}
});
Hope this help. Your ajax should work now.
Have you a route for AJAX requests? (I don't see it.)
Please try following code:
In your AJAX code:
$.ajax({
type: "POST",
url: "{{ route('ajax_route') }}",
data: { _token: "{{ csrf_token() }}", data: "sample data" },
success: function(data){
$(".result").html(data);
},
dataType: "json"
});
In your controller code:
public function ajaxAction(Request $request){
if ($request->isXmlHttpRequest() && $request->isMethod('post')) {
$data = $request->input('data', null);
echo json_encode($data);
}
}
In your route code:
Route::post('/ajax_route', ['as' => 'ajax-action', 'uses' => 'YourController#ajaxAction']);
I have a simple input box in a form the value of which I'm trying to send to django via Ajax post, but I'm getting a 500 error ValueError at /rest/
Cannot use None as a query value
<form onsubmit="return false;">
{% csrf_token %}
Search:<input type="text" name="artist" id="artist" />
<button class="updateButton" onclick="createlist()">submit</button>
</form>
<script>
function createlist(){
$.ajax({
type: "POST",
url: "/rest/",
dataType: "json",
data: {
csrfmiddlewaretoken: "{{ csrf_token }}",
artist: $('#artist').val()
},
success: function(data){
$('body').append(data.results);
}
});
}
</script>
View:
def rest(request):
artistname = request.POST.get("artist") # <- problem here?
response_data = {}
query_results = Art.objects.filter(artist__contains=artistname)
response_data['results'] = query_results
return HttpResponse(json.dumps(response_data), content_type="application/json")
When I check the headers under Form Data it shows artist: da vinci which is what I typed in. Where is the train getting derailed?
copy, pasted your code and worked for me.
You can try and changing the way you send the POST request.
$.ajax({
type: "POST",
url: "/rest/",
dataType: "json",
data: {artist: $('#artist').val() },
headers: {
'X-CSRFTOKEN': "{{ csrf_token }}",
},
success: function(data){
$('body').append(data.results);
}
});
I figured out the problem. My app/urls.py file was sending the url to the wrong function. I thought the /rest/ url was going to the views.rest function, but for some reason /rest/ was being sent to views.get_search_entry which does something completely different with post requests.
from django.conf.urls import patterns, url
from myapp import views
urlpatterns = patterns('',
url(r'^$', views.get_search_entry, name='get_search_entry'),
url(r'^results/', views.get_search_entry, name='result'),
url(r'^rest/', views.rest, name='rest'),
)
Then I had to serialize the queryset before dumping to json to send over the wire.