简体   繁体   中英

Using PUT method AJAX results in empty $request->all() array in Laravel 6

I have a very simple form for testing purposes, when I try to PUT the formData using $.ajax I get a empty array response but this happen only when I use PUT method, if I use POST instead of PUT method works as expected.

I'm using Laravel 6, I have a var_dump in each function:

var_dump($request->all())

When I use PUT method I get:

array(0) {}

When I use POST method I get:

array(4) { ["form1"]=> string(1) "1" ["form2"]=> string(1) "2" ["form3"]=> string(1) "3" ["form4"]=> string(1) "4" } 

I need the formData because I going to PUT image files. I was looking for another similar questions but no one solves my issue.

There are another method to perform this?


<form id="formTest" type="multipart/form-data">
    <input name="form1" value="1">
    <input name="form2" value="2">
    <input name="form3" value="3">
    <input name="form4" value="4">
    <button type="submit">Accept</button>
</form>

<script>
    $(document).ready(function () {
        $('#formTest').on('submit', function (e) {

            e.preventDefault();

            var formData = new FormData($(this)[0]);

            $.ajax({
                url: '<?echo($config->get('apiUrl'))?>movies/13',
                type: 'PUT',
                processData: false,
                contentType: false,
                data: formData,
                success: function(result)
                {
                },
                error: function(data)
                {
                    console.log(data);
                }
            });
        });

    });
</script>

Try adding these two input fields in your form.

<input type="hidden" name="_method" value="PUT">
<input type="hidden" name="_token" value="{{ csrf_token() }}">

The first one is changed the form submission method to "PUT" and the second one is including the CSRF Token to the form.

Then in your AJAX code, change the type: 'PUT' to type: 'POST' .

$.ajax({
    url: '<?echo($config->get('apiUrl'))?>movies/13',
    type: 'POST',
    processData: false,
    contentType: false,
    data: formData,
    success: function(result) {},
    error: function(data) {
        console.log(data);
    }
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM