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

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
}
});

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.

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>

How laravel set path for ajax and forms

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') }}"
});

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?">

django form wizard ajax next step

I am creating a 9-step proposal form using django form wizard. All is well, until I wanted to use ajax to load the next step. I'm having a hard time configuring the ajax call in jquery because django forms don't have action url included in the form tag. Why is it like that anyway? A win-win situation for me is to have a loading screen for next step and if there is an upload file process in the step, show percentage loading for the uploaded file. Thanks!
I'm using this code, and It's working for me. I don't put any action inside the form, as you can see. I use the jquery 'on' function when the form is submited because all the form is reloading and changing inside the div#creation. Then the ajax url must be the one that displays your form.
In my case, the first step of the form is rendered also through ajax with get, when I click on some button. That's why there's isn't any form in the div at first. (I'm using bootstrap's modals).
<div id="creation">
<!-- form to be display through ajax -->
</div>
The template that is reload in the FormWizard Class in views is the following html:
template_name = 'creation_form.html'
Code por creation_form.html:
<form id="creation-form" action="#" method="post">
{% csrf_token %}
<table>
{{ wizard.management_form }}
{{ wizard.form }}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" class="btn btn-primary" aria- hidden="true" type="submit" value="{{ wizard.steps.first}}">First</button>
<button name="wizard_goto_step" class="btn btn-primary" aria-hidden="true" type="submit" value="{{ wizard.steps.prev}}">Previous</button>
{% endif %}
<input id="create-submit" class="btn btn-primary" type="submit" value="submit" />
</form>
Here is my ajax call:
$('#creation').on('submit', '#creation-form' , function(e){
e.preventDefault();
var fd = new FormData($('#creation-form').get(0));
$.ajax({
url: '/create/',
data: fd,
type: "POST",
success: function(data){
$('#creation').html(data);
},
processData: false,
contentType: false
});
});
Hope this is a proper response for your answer.
I'm currently having a hard time going to the first/previous step, if you figure it out please tell me how.
This is what you're looking for?
Here's what I did-
Created separate model forms for each step.This helped in easy server side validation.
Made ajax calls for each step to validate form on the server side and on success render the next form and hide the previous form.
On submit of last form async POST the data for persistence and processing and render the response asynchronously below the last step.
Also maintained a progress bar for each step.
This is how I created my async form wizard using django forms. Not neat but works! :)

Resources