How laravel set path for ajax and forms - ajax

I have simple question:
How laravel set correct path for ajax or form action?
I have my laravel instalation in
localhost/laravel-test/public
Ok and lets say i have url opened: localhost/laravel-test/public/hello
<form method="post" action="some/very/long/path">
<input type="submit" value="just-test" />
</form>
Now i hit just-test button, and its always know where it should start routing - allways start from public/[route here].
I was try to do my own routing system, but i have problem because its going to addres:
localhost/my-framework/public/hello/some/very/long/path
It allways put after public my actual url, and then after form action..
So my question is how laravel know it should get
localhost/laravel-test/public/some/very/long/path
It works same for jquery ajax request for ex:
$.ajax({
url: "test.html",
context: document.body
})
Laravel console output:
localhost/laravel-test/public/test.html
My custom framework console output
localhost/my-framework/public/actualpath/test.html

For the form action you can use the url or route helper. Like so:
{{ url('very/long/path') }}
And for your front end part.
$('#form').live('submit', function(event) {
$form = $(this);
$.ajax({
url: $form.attr('action')
});
});

I think this is what you're looking for.
In routes.php
Route::post('some-very-long-uri', ['as' => your-name', 'uses' => 'YourController#method']);
Then you can do something like that
<form method="post" action="{{ route('your-name') }}">
<input type="submit" value="just-test" />
</form>
and for ajax
$.ajax({
url: "{{ route('your-name') }}"
});

Related

I can't send file through an ajax PUT request, using Laravel

I have a form with an input of type file hidden. An image tag works as the clickable trigger to select the file itself, with js to trigger it (that works), but I want to automatically make a PUT request as one chooses an image instead of having to click a submit button on the form, every time the image is changed on the input field. I'm using ajax for that, but at the controller endpoint that processes the request, I don't seem to have any file. If I put other fields such as textual they seem to pass into the controller through the request just fine, though.
My route:
Route::put('/coins/image/{key}', [CoinController::class, 'image'])->name("coins.image");
My controller (no actual image-updating code yet; just what I'm doing to check for the file):
public function image(int $key)
{
dump(request()->file('file'));
dump(request()->file);
dump(request());
}
My HTML and JS in the following snippet:
function promptImageForUpload(elemId)
{
$('#' + elemId).click();
}
function uploadImage(event, imgId, key)
{
event.preventDefault();
var inputElem = event.target;
var imageFile = inputElem.files[0];
var imgElem = $('#' + imgId);
var form = $(inputElem).parent();
var formData = new FormData(form[0]);
formData.append('file', imageFile);
$.ajax({
url: "/coins/image/" + key,
type: "PUT",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: formData,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(response) {
var reader = new FileReader();
reader.onload = function(e) {
imgElem.attr("src", e.target.result);
};
reader.readAsDataURL(imageFile); // convert to base64 string
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="card-body">
<form data-key="0" id="coin-header-0_form" method="POST" action="#" enctype="multipart/form-data">
<input type="file" name="file" id="coin-header-0_file" style="z-index:-1; width: 100%; height: 100%; display: none;" onchange="uploadImage(event, 'coin-header-0_preview', 0)">
<input type="hidden" name="_method" value="PUT">
<meta name="csrf-token" content="7c3s2NmosdK9qzrS10xGAB0rYXw5g41azRjcmPQC">
<img src="http://snapbuilder.com/code_snippet_generator/image_placeholder_generator/60x40/007730/DDDDDD/this%20pict" width="50px" height="50px" alt="icon" id="coin-header-0_preview" onclick="promptImageForUpload('coin-header-0_file');">
</form>
</div>
For now, I am force-updating the preview of the image on the ajax success instead of retrieving it from the updated entity upon successful update, to avoid a second query.
I have the method set to PUT for spoofing in the ajax request and the xsrf token set the headers as well.
Enctype is set to multipart/form-data for files too. I have no clue as to why I don't see the uploaded file anywhere in the request.
Using Laravel Framework 8.25.0, jquery 3.5.1.
Please let me know if any more info is needed, anyone.
I couldn't find any solution on any stackoverflow entry or elsewhere that regards this subject.
Any help is greatly appreciated since I don't really how else to look at this in a debugging approach.
HTML forms do not support PUT, PATCH or DELETE actions. So, when defining PUT, PATCH or DELETE routes that are called from an HTML form, you will need to add a hidden _method field to the form. The value sent with the _method field will be used as the HTTP request method:
<form action="/foo/bar" method="POST">
<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
</form>
You may use the method_field helper to generate the _method input:
{{ method_field('PUT') }}
In the same way, this check may also affect ajax forms. Then in your form switch to the POST method and set the PUT parameter for it to work.

How to convert laravel form delete into string to use it on return controller?

I have delete form but I can't use directly on blade cause I am using datatable and it just there to put the code of the form.
This is the code of delete that I want to copy
<form action="{{ route('admin.users.destroy', $user->id)}}" method="post">
#csrf
#method('DELETE')
<button class="btn btn-danger" type="submit">Delete</button>
</form>
and I want to put/swap in the red circled image below cause <a href="'.route('admin.users.destroy', $user->id).'" used GET and not DELETE method.
I believe you need to use the ajax call instead of call it through the link you can ajax call as below and it will DELETE resource.and then refresh the datatable
$.ajax({
url: '/admin/users/4',
type: 'DELETE', // user.destroy
success: function(result) {
// Do something with the result
// refresh the datatable
}
});

Laravel vue axios is action method and csrf needed for ajax forms

I am posting a ajax from in Laravel using axios and vue, I have a #click="postData" button in the form that toggles a axios post request:
postData() {
axios({
method: 'post',
url: appJS.base_url + '/comment',
responseType: 'json',
data: comData
})
.then(function(response) {
})
But do I still need to add the action, method and csrf to my form?
<form action="{{ url('/comment') }}" method="POST">
{{ csrf_field() }}
</form>
vs
<form></form>
Everything works fine just using <form></form> but I wonder if there are any pros/cons?
I am making a ajax call in the background since I dont want the whole page to reload
You definitely don't need action and method attributes on form tag, because they are already defined on your axios call.
As for the csrf_field(), you probably still need it, because Laravel has a preconfigured middleware called VerifyCsrfToken. But it depends if you use it or not.
you can using event form in vuejs, you need't using ajax, you can try the following code, but if laravel + vuejs, need add Enable CORS for a Single Route in laravel:https://gist.github.com/drewjoh/43ba206c1cde9ace35de154a5c84fc6d
export default{
data(){
return{
title:"Form Register",
}
},
methods:{
register(){
this.axios.post("http://localhost:8888/form-register",this.formdata).then((response) => {
console.log(response);
});
},
}
}
<form action="" method="post" v-on:submit.prevent="register">
<div class="panel-heading">{{title}}</div>
<div class="form-group">
<button type="submit" class="btn btn-danger">Register</button>
<button type="reset" class="btn btn-success">Reset</button>
</div>
</form>

Vue-Resource gives TokenMismatchException in Ajax POST call

Please note, I'm using the Laravel framework.
Also please note, there are similar questions on SO, I've checked them, but wasn't able to solve my problem based on those solutions...
Even though I set my CSRF token right to my knowledge, I'm not sure why it won't work.
When checking the console, it seems I have 3 cookies: two Request cookies of which one is called XSRF-TOKEN and one is called laravel_session. And one respone laravel_session cookie. All have a different value!!!
My Vue:
new Vue({
el:'body',
http: {
root: '/root',
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
},
});
My head:
<meta name="_token" content="{!! csrf_token() !!}"/>
My Vue component addNew method:
Vue.component('things',{
template:'#things-panel-template',
data(){
return {
list: [],
newThing: {
body: '',
// _token: $('meta[name=_token]').attr('content'),
// tried removing token from head meta and adding up here.
},
}
},
methods:{
addNew(){
var thing = this.newThing; // get input
this.newThing = {body:''}; // clear input
this.$http.post('/api/things/add',thing) // send
},
},
});
My route:
Route::post('/api/things/add',function(){
return App\Thing::create(Request::get());
});
And finally, the form in my Vue Template:
<form action="/things/add"
method="POST"
#submit.prevent="addNew"
>
<div class="form-group">
{{ csrf_field() }}
<label for="">Add</label>
<input type="text"
name="body"
id="task-body"
class="form-control"
v-model="newThing.body"
>
<button :disabled="!isValid"
class="btn btn-primary"
type="submit"
>Add</button>
</div>
</form>
Try this:
this.$parent.$http.post('/api/things/add', thing)
instead of
this.$http.post('/api/things/add', thing)
Or set default values using the global configuration:
Vue.http.headers.common['X-CSRF-TOKEN'] = $('meta[name=_token]').attr('content');
I found the answer myself:
If you're gonna work with a vue-component, you should just add the token to that component instead. Otherwise it won't go with your ajax request.
So put this part underneath the template in the component:
http: {
root: '/root',
headers: {
'X-CSRF-Token': $('meta[name=_token]').attr('content')
}
},
Do this to check if your token was properly sent inside the headers:
Go to google chrome, open dev-tools, go to the network tab and Reload.
Make the ajax call and look at the file added in the network tab, open it and go to the 'Headers' tab.
Look at the bottom where it says: 'Request Headers' and check if the token was properly added in the request.

HTML DELETE Method on a single button

I'm using Laravel with a Route::resource() controller and to delete something it needs to run the function destroy(). This method requires a DELETE HTTP method to go off. How do I do this on a single button?
Thanks
You can create a form around the delete button. This will not add anything to the page visually.
For example:
{{ Form::open(['url' => 'foo/bar', 'method' => 'delete', 'class' => 'deleteForm']) }}
<input type="submit" class="deleteBtn" />
{{ Form::close() }}
The Laravel Form helper automatically spoofs the form and adds the hidden field for the DELETE method.
Then you can style the button using the .deleteBtn class. If the button needs to be positioned inline, you can even assign a display: inline; property to the .deleteForm class.
You could add a form and use Laravel's Form Method Spoofing
<input type="hidden" name="_method" value="DELETE">
or you could use ajax (Example code below uses jQuery)
$.ajax({
url: 'YOUR_URL',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
You could also use this library https://gist.github.com/soufianeEL/3f8483f0f3dc9e3ec5d9 to implement this:
<a href="posts/2" data-method="delete" data-token="{{csrf_token()}}" data-confirm="Are you sure?">

Resources