Using multipart/form-data header to upload files using vuejs, laravel, axios causes 401 - laravel

I am trying to upload file using axios library.
axios.post('/images/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then( response => console.log(response))
Route::middleware('auth:api')
->group( function() {
Route::post('/images/upload', 'ImageController#store');
})
I get the following error with status code
{"message": "unauthenticated"}
The moment I remove the header part i.e. "multipart/form-data", the request goes through, but that's no bueno since I need to send the file as well.

I found the problem when trying to reproduce this
Send a Bearer header with the api_token in the header
for example
<meta name="csrf-token" content="{{ csrf_token() }}">
<div id="app">
<input type="file" name="image" id="image" onchange="upload()">
</div>
<script src="{{ asset('js/app.js') }}" defer></script>
<script>
function upload() {
let image = document.getElementById('image').files[0];
let formData = new FormData();
formData.append('image', image);
axios.post('/images/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data',
'Authorization': 'Bearer {{ auth()->user()->api_token }}',
}
}).then( response => console.log(response))
}
</script>
Assuming a controller function like this
public function store(Request $request)
{
$path = $request->file('image')->store('public');
return $path;
}
You would get the stored image url in the response
Hope this helps :)

Related

ajax post with laravel 5.6

I can't figure out how to get this ajax request to post.
<button class="btn btn-sm btn-primary" id="ajaxSubmit">Submit</button>
<textarea rows="4" class="form-control resize_vertical" id="application_notes" name="application_notes" placeholder="Notes">{{$application->notes}}</textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
var url = "/instructor-notes-save/{{$application->id}}"
$(document).ready(function(){
$('#ajaxSubmit').click(function(e){
e.preventDefault();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
$.ajax({
url: url,
method: 'post',
data: {
application_notes: jQuery('#application_notes').val(),
},
success: function(response){
console.log(response);
}});
});
});
</script>
My controller is this:
public function saveNotes(Request $request, $id)
{
$application = Application::findOrFail($id);
$application->notes = $request->application_notes;
$application->save();
return response()->json(['success'=>'Data is successfully added']);
}
And for what it's worth, here is my route:
Route::post('/instructor-notes-save/{id}', 'InstructorsController#saveNotes')->name('instructor.save.note');
What am i missing to get this ajax request to work? In my console log, i get a 419 unknown status error.
Kindly check that the meta tag _token is present in your layout file inside the <head> tag.
Also please make sure that the AJAX url is present in your routes file.
add the following tag in your html <head>:
<meta name="csrf-token" content="{{ csrf_token() }}">

Request of Ajax with Laravel 5.4

I am trying to make an example of Ajax request with Laravel 5.4.
The test example is simple, just enter a numeric value in an input = text field in my View and leave the field to send to the Controller, then add + 10 to that value and then return that value to my View so that it can displayed on an alert.
HTML : viewteste.blade.php
<!DOCTYPE html>
<head>
<title></title>
</head>
<body>
<form action="">
Valor: <input type="text" id="valor" name="valor" />
</form>
</body>
</html>
JS: The js file is inside viewteste.blade.php, I just split it to make it easier to interpret.
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$("#valor").on('blur', function()
{
valor = $(this).val();
$.ajax({
type:'POST',
url:"{{ URL::to('/teste/valor') }}",
dataType: 'JSON',
data: {
"valor": valor
},
success:function(data){
alert('Success');
},
error:function(){
alert('Error');
},
});
});
});
</script>
Route
Route::get('/teste', 'TesteAjaxController#index');
Route::post('/teste/valor', 'TesteAjaxController#valor');
Controller
class TesteAjaxController extends Controller
{
public function index()
{
return view('painel.viewteste');
}
public function valor(Request $request)
{
$valor= $request->input('valor');
$valor += 10;
return $valor; // How do I return in json? in case of an error message?
}
}
Always when I try to send the request via ajax it goes to alert ('Error'). is it that I'm doing something wrong in sending the ajax or route?
to return a json response. you need to use.
response()->json([
'somemessage' => 'message',
'valor' => $valor
]);
UPDATE: you are getting an error alert because i think your route method doesnt match your controller methods.
Route::post('/teste/valor', 'TesteAjaxController#valor');
where in your controller you have
public function cep() ...

Laravel live ajax search - token mismatch

I am making a live search where user can search for business.
This would be done using ajax and display results however I get an error that there is an TokenMismatchException.
Here's my code:
Ajax:
function search_data(search_value) {
$.ajax({
url: '/searching/' + search_value,
method: 'POST',
headers: {
'X-CSRFToken': $('meta[name="token"]').attr('content')
}
}).done(function(response){
$('#results').html(response); // put the returning html in the 'results' div
});
}
Controller:
public function search($search) {
$search_text = $search;
if ($search_text==NULL) {
$data= Business::all();
} else {
$data=Business::where('name','LIKE', '%'.$search_text.'%')->get();
}
return view('results')->with('results',$data);
}
}
Route::
Route::get('/', function () {
return view('auth/login');
});
Route::group(['middleware' => ['auth']], function () {
Route::get('tfgm', 'GuzzleController#tfgm')->name('tfgm');;
Route::get('odeon', 'GuzzleController#odeon')->name('odeon');;
Route::get('chronicle', 'GuzzleController#oldham_chronicle')->name('chronicle');;
Route::get('smokeyard', 'GuzzleController#smokeyard')->name('smokeyard');;
Route::get('profile/', 'ProfileController#checkid')->name('profile');;
Route::get('create/business', 'BusinessController#addBusiness')->name('createBusiness');
Route::get('business/list', 'BusinessController#viewBusiness')->name('viewBusiness');
Route::get('business/{id}', 'BusinessController#displayBusiness')->name('displayBusiness');
Route::post('/searching/{search}', 'SearchController#search');
Route::post('update', 'ProfileController#updateProfile');
Route::post('create', 'BusinessController#createBusiness');
Route::post('image', 'ImageController#image');
Route::post('test2', 'ImageController#gallery');
Route::post('markers', 'BusinessController#saveMarkers');
Route::post('reviews', 'BusinessController#saveReviews');
});
Auth::routes();
Route::get('/home', 'HomeController#index')->name('home');
Route::get('/redirect/{provider}', 'SocialAuthController#redirect');
Route::get('/callback/{provider}', 'SocialAuthController#callback');
master.blade.php
<head>
<meta name="csrf-token" content="{{ csrf_token() }}" />
</head>
<form action="/search" method="get" autocomplete="off" class="navbar-form navbar-left">
<div class="form-group">
<input type="text" class="form-control" id="search_text" onkeyup="search_data(this.value, 'result');" placeholder="Search">
</div>
<div id="result">
#include('results')
</div>
</div>
</form>
Your line must be
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
In your ajax code you have written X-CSRFToken that is wrong. Correct is X-CSRF-TOKEN
Always use below code in you script file
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
Change X-CSRFToken to X-CSRF-TOKEN

Ajax laravel 5.2 doesn't work

I want to develop simple ajax with laravel5.2 with this code
This oneline_help.php view
<html>
<head>
<title>Ajax Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
</head>
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<?php
echo Form::button('Replace Message',['onClick'=>'getMessage()']);
?>
</body>
</html>
This is the routes
Route::get('/ajax','front#support');
Route::post('/getmsg','Hello#index');
This is front #support
public function support()
{
return view('online_help', array('title' => 'Welcome', 'description' => '', 'page' => 'online_help','subscribe'=>"",'brands' => $this->brands));
}
This is Hallo #index controller
public function index(){
echo"i in in hello index";
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
The button appear But when click on it, The text doesn't change .
Please tell me why and how to resolve it.
Here is my working example of AJAX....
You don't need to add token in your ajax request, make it global so with every ajax request, your CSRF token will be added automatically.
In your HTML Head section add this meta tag
<meta name="csrf-token" content="<?php echo csrf_token() ?>">
Then add this code in your Javascript tags. this will add CSRF token in every ajax request.
Note this required jquery file should be included in your page. once include call this method below from the file.
<script type="text/javascript">
var csrf_token = $('meta[name="csrf-token"]').attr('content');
$.ajaxSetup({
headers: {"X-CSRF-TOKEN": csrf_token}
});
</script>
I have modified your method....
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>', //remove this line
dataType:'json', // you skipped this line
beforeSend:function(){
alert('loading....'); //this will show loading alert
},
success:function(data){
$("#msg").html(data.msg);
},
error:function(){
alert('loading error...')
}
});
}
</script>

Laravel AJAX 500 Internal Server Error, Tokens Match

When I submit the form, I get this error and the page automatically reloads, but the url in the browser then shows my route and content that I posted in the form. Then, if I go ahead and submit again without reloading the page it works just fine. Could it be that I'm not posting the token itself? I have added the meta tag to the head.
<meta name="csrf-token" content="{{ csrf_token() }}" />
JS:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#postForm').submit(function(){
var body = $('#postbody').val();
var profileId = $('#user_id').text();
$.ajax({
type: "POST",
url: "/post/"+profileId,
data: {post:body, profile_id:profileId},
success: function(data) {
console.log(data);
}
});
});
Route:
Route::post('/post/{id}', [
'uses' => '\App\Http\Controllers\PostController#postMessage',
'as' => 'post.message',
'middleware' => ['auth'],
]);
Controller:
public function postMessage(Request $request, $id)
{
if(Request::ajax())
{
$this->validate($request, [
'post' => 'required|max:1000',
]);
$newMessage = Auth::user()->posts()->create([
'body' => $request->input('post'),
'profile_id' => $id
]);
}
}
View:
<form role="form" action="#" id="postForm">
<div class="feed-post form-group">
<textarea class="form-control feed-post-input" id="postbody" name="post"></textarea>
<div class="btn-bar">
<button type="submit" class="btn btn-default btn-post"></button>
</div>
</div>
<input type="hidden" name="_token" value="{{ csrf_token() }}"/>
</form>
UPDATE:
So, the log says that "Request::ajax() should not be called statically" in my controller. I removed that code and it works fine now. However, I want to know if removing it is ok to do of if there's a better way to resolve this. Thanks!
ANSWER: It works by changing
if (Request::ajax()){
// code...
}
to
if ($request->ajax()){
// code...
}
Change Request::ajax() to $request->ajax()
You are doing an AJAX post – you are not supposed to be redirected anywhere at all. If there is an error – you should only see it in Developers Tools in your browser.
Try adding:
$('#postForm').submit(function(e) {
e.preventDefault();
...
}
So that browser doesn't post the form instead of your AJAX call. Also try fixing your header case: X-CSRF-TOKEN to X-CSRF-Token
Also, your postMessage() method doesn't return anything at all. You should probably notify the user of the result there or just return $newMessage.

Resources