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>
2
  • Are you using Route::put() in your routes file? Commented Oct 18, 2019 at 21:35
  • @MatMorici yes, for PUT I'm Using: Route::put('movies/{id}','MoviesController@update'); And for POST: Route::post('movies','MoviesController@add'); Commented Oct 18, 2019 at 21:58

1 Answer 1

4

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);
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

After suffering for hours, just found the perfect solution.
Yea just add this line in your form, you are good to go: <input type="hidden" name="_method" value="PUT">

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.