Raj
Raj

Reputation: 2028

Simple Ajax Post in laravel 5 not working

Im using a very simple form to send ajax post request but its showing a 500 (internal server error) in the console and when i click that link it opens a file and shows error is in this line

// Do send the request (this may raise an exception)
xhr.send( options.hasContent && options.data || null );

The page which sends the request is demotest.blade.php

The URL that receives the request is ajaxpage, it forwards it to AjaxController@postData

Here is my web.php file

Route::get('/demotest', function(){
    return view('admin/posts/demotest');
});

Route::post('/ajaxpage', 'AjaxController@postData');

Here is my demotest.blade.php file

@extends('layouts.app')

@section('content')
    <div class="container">
        <div class="row">

        <form id="myform" method="POST" action="{{ url('/ajaxpage') }}">
            {!! csrf_field() !!}

            <input id="token_field" name="_token" type="hidden" value="{{csrf_token()}}">

            <input id="firstname" type="text" name="firstname" />
            <input type="submit" value="submit" />
        </form>

        <div id="display_here"></div>

        </div>
    </div>
@endsection

@section('jscript')

<script>

    $( document ).ready(function() {

        // for csrf protection when using ajax
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
            }
        });

        $('#myform').on('submit', function (e) {

            e.preventDefault();

            var firstname = $("#firstname").val();

            $.ajax({
                type: "POST",
                url: "/ajaxpage",
                data:{
                    firstname: firstname,
                    _token: $('#token_field').val()
                  },
                dataType : 'json',
                success: function( data ) {
                    console.log(data);
                    $('#display_here').html(data);
                }
            });

        });
    });

</script>

@endsection

It consist of a single field and submit button and jquery for sending ajax request

Here is the controller which handles the request

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class AjaxController extends Controller
{
    public function postData(Request $request)
    {
        return Response()->json($request::all());
    }
}

This is it. Still im getting an error. Please help me solve this problem.

Upvotes: 0

Views: 1030

Answers (2)

Nazmus Shakib
Nazmus Shakib

Reputation: 832

You need to use $request as an array or object of form attributes. Using multiple csrf_token in a form is not necessary. A single random unguessable token per session is sufficient.

Upvotes: 0

Leo
Leo

Reputation: 7420

If you open up network inspector and check XHR requests you will see an error response, because you are calling method all() static over an array that contains the request attributes.

So to fix your error instead of

return Response()->json($request::all());

do

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

or just for a sanity check do:

return response()->json(['success'=>true]);

so when you open up console on your browser you should have the response.

Upvotes: 1

Related Questions