My view like this :
<input type="file" style="display: none" id="test">
When the file called, it will call ajax
I put my ajax in main.js (myshop\\resources\\assets\\js\\main.js)
It is global js. I put all my js there. I also put my ajax there
I put my ajax in main.js like this :
var _token = $('input[name="_token"]').val();
console.log(_token);
$('#test').on("change", function(){
data = new FormData();
$.ajax({
url: window.Laravel.baseUrl+'/product/addImage',
type: "POST",
data: { data: data, _token: _token },
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false // tell jQuery not to set contentType
}).done(function(data) {
console.log(data);
});
});
My routes like this :
Route::post('product/addImage', 'ProductController@addImage');
My controller like this :
public function addImage(Request $request)
{
dd('test');
// dd($request->all());
}
When executed, the console tab exist error like this :
POST http://myshop.dev/product/addImage 500 (Internal Server Error)
and on the network tab exist error like this :
TokenMismatchException in VerifyCsrfToken.php line 68:
How can I solve the error?
Whether ajax can be placed in global js?
You can resolve this issue in two ways:
You could use
<meta name="csrf-token" content="{{ csrf_token() }}" /> // add this under head tag
And before Ajax call add this:-
$.ajaxSetup({
headers:
{
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Or the other (simpler) way, inside your app\\Http\\Middleware/VerifyCsrfToken.php
add
protected $except = [
'product/addImage',
];
Hope it helps!
Remember to add file to data
data = new FormData();
data.append("test", $("#fileInput")[0].files[0])
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.