Laravel Ajax JSON Object is empty

I'm working on a laravel web app, I'm relatively new to laravel so I'm not very familiar with the ajax tokens and such, but I believe I have set it up correctly.

Below is my Ajax code for a test page that I want to try and send data from.

<meta name="csrf-token" content="{{ csrf_token() }}">

<script type="text/javascript">
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
</script>

<script type="text/javascript">
    $(document).ready(function () {
        $('#btn').on('click', function (e) {
            e.preventDefault();

            $.ajax({
                type: 'POST',
                url: 'testSend',
                data: {
                    test: 'hello'
                },
                dataType: 'json',
                success: function (response) {
                    alert(response);
                },
                error: function (data) {
                    console.log('Error:', data);
                }
            });
        });
    });
</script>

Here is my form:

<div class="flex-center position-ref full-height">
<div class="content">
    <form action="testSend" method="post" enctype="multipart/form-data">

        <button type="submit" id="btn"> submit</button>
    </form>
</div>

And here is a simple route that I have setup just to test this:

Route::post('testSend', function (Request $request) {
    return response()->json($request);
});

However when I go to check the network in chrome, the JSON Object is empty.

The empty JSON Object:

The empty JSON Object

I'm pretty new to this, I have learned it but never really tried to create a web app until now. I have searched everywhere, but no one seemed to have the same problem, maybe they did but I just don't know.

The problem might just be a dumb mistake, but I really can't figure it out ):

Thanks.

1 answer

  • answered 2018-01-14 09:49 kazimt9

    Rather than passing Request instance try this:

    return response()->json($request->all());