How to do ajax in Laravel 5.2

Date Posted: July 26, 2016, 11:36 am


  1. Create a dummy button on your view:
    1
    2
    <input type = "submit" class = "btn btn-primary m-d do-ajax" value = "AJAX" />
    {{ csrf_field() }} {{-- This will include a unique token which will we will pass along with our AJAX post --}}
  2. On your JS script, add the following:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    $('body').on('click', '.do-ajax', function () {
        $.ajax({
            url: './page/do-ajax',
            headers: {'X-CSRF-TOKEN': $('input[name=_token]').val()},
            data: {
                test: 'test'
            },
            type: 'POST',
            datatype: 'JSON',
            success: function (resp) {
                alert(resp);
            }
        });
    });
  3. On your controller add this new method:
    1
    2
    3
    4
    5
    6
    7
    public function do_ajax(Request $request) {
        if( $request->ajax() ) {
            return response()->json([
                'testdata' => 'it works!'
            ]);
        }
    }
  4. On your route, add the following code:
    1
    Route::post('/page/do-ajax', 'PageController@do_ajax');
  5. Try it out, click the button. You should get the response of the ajax request: “it works!”.

About author


Carl Victor Fontanos

A fine gentleman specializing in front-end and back-end development with extensive experience building high performance web applications that keeps users engaged and help businesses grow.

 
Hire Me