Asked by: Azima
I'm submitting form data with ajax and I'm getting this token mismatch error while still passing token. Here's my code snippet:
var _csrfToken = $('meta[name=token]').attr('content');
var link = $('meta[name=url]').attr('content');
// $.ajaxSetup({
// headers: {
// 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
// }
// });
$('#upload_form').submit(function(e)
{
e.preventDefault();
var title = $('#title').val();
var designation = $('#position').val();
var category = $('#category').val();
var azimaData = {
name: title,
designation: designation,
category: category,
_token: _csrfToken
};
console.log(azimaData);
$.ajax({
method: 'POST',
url: link + '/@dashboard@/galleryImage/add_image',
data: azimaData,
//use contentType, processData for sure.
contentType: false,
processData: false,
success: function(msg) {
if(msg.status == success)
{
alert(msg.msg);
}
else
{
alert(msg.msg);
}
},
error: function(xhr) {
console.log(xhr);
}
});
});
Other Ajax requests are working fine with the token issue. Where did I go wrong with this one?
Answers
Answered by: Arigi Wiratama at 2017-07-11 06:45PM
Change your meta name
. It should be something like this
var _csrfToken = $('meta[name=_token]').attr('content');
Answered by: Hitesh Dingankar at 2017-07-11 08:08PM
You cannot send data in an object form, while after setting the contentType and processData options to false. So in this scenario, you can send the data either by serializing the form or by creating a new FormData instance and appending the data to it manually.
I have edited your code. And have used FormData for sending the data along with the token.
$('#upload_form').submit(function(e)
{
e.preventDefault();
var title = $('#title').val();
var designation = $('#position').val();
var category = $('#category').val();
var azimaData = new FormData(); // create a new FormData..
azimaData.append('name', title);
azimaData.append('designation', designation);
azimaData.append('category', category);
azimaData.append('_token', _csrfToken);
$.ajax({
method: 'POST',
url: link + '/@dashboard@/galleryImage/add_image',
data: azimaData,
//use contentType, processData for sure.
contentType: false,
processData: false,
success: function(msg) {
if(msg.status == success)
{
alert(msg.msg);
}
else
{
alert(msg.msg);
}
},
error: function(xhr) {
console.log(xhr);
}
});
});
Answered by: linktoahref at 2017-07-11 08:31PM
Try the ajax request by removing contentType: false
and processData:false
from your ajax request.
$.ajax({
method: 'POST',
url: link + '/@dashboard@/galleryImage/add_image',
data: azimaData,
success: function(msg) {
if(msg.status == success) {
alert(msg.msg);
} else {
alert(msg.msg);
}
},
error: function(xhr) {
console.log(xhr);
}
});
No comments:
Post a Comment