How to send form containing files via jQuery ajax using PATCH method to Laravel 5?

旧街凉风 提交于 2021-01-27 22:51:50

问题


This is my code:

 //routes.php
Route::match(['post', 'patch'],'/slide/{id}', function() {
    dd(request()->all());
});

//form
<form id="form" enctype="multipart/form-data">
    <input type="text" name="title">
    <input type="file" name="image">
</form>

//js
$('#form').on('submit',(function(e) {

    $.ajax({

        type: "PATCH",
        url:'/slide/' + id,
        data: new FormData(this),
        cache: false,
        contentType: false,
        processData: false

    }).done(function(r) {

        console.log(r);

    });
}));

When I use POST method everything is fine and dd(request()->all()) returns:

array:2 [
  "title" => "foo"
  "file" => UploadedFile {#400
    -test: false
    -originalName: "bar.png"
    -mimeType: "image/png"
    -size: 4413
    -error: 0
    ...
  }
]

but when change method to PATCH i receive empty array.

Can someone explain what am I doing wrong and share proper way of sending FormData via ajax using PATCH method to L5?

Im using Laravel 5.2 and jQuery 2.2.3


回答1:


You can do this named method spoofing. this trick is what Laravel does in its forms. if you want to send patch request you can put this line in your code.

<input type="hidden" name="_method" value="PUT">

you can read more about method spoofing here.




回答2:


I had a similar issue while sending a form using AJAX. I used the formData.append() function to add the _method field to the FormData() before sending.

In your code it would look like this:

$('#form').on('submit',(function(e) {
  var formData = new FormData(this);

  formData.append('_method', 'patch');  
  $.ajax({
    type: "POST",
    url:'/slide/' + id,
    data: formData,
    cache: false,
    contentType: false,
    processData: false
  }).done(function(r) {
  console.log(r);
});



回答3:


The solution with the hidden input is the correct one. The docs explain this nicely.

But another problem is, that the $request array is not available in its calling context. Laravel will recognize this parameter and pass it to your Closure in the following:

Route::match(['post', 'patch'],'/slide/{id}', function($request) {
  dd(request()->all());
});


来源:https://stackoverflow.com/questions/40127289/how-to-send-form-containing-files-via-jquery-ajax-using-patch-method-to-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!