Minimum Working Example for ajax POST in Laravel 5.3

I presume you have a basic understanding of the model-controler-view paradigm, a basic understanding of Laravel and a basic understanding of JavaScript and JQuery (which I will use for reasons of simplicity).

We will create an edit field and a button which posts to the server. (This works for all versions from Laravel 5.0 to 5.6)

1. The Routes

At first you need to add routes to your routes/web.php. Create one route for the view, just as you know from ordinary views:

Route::get('ajax', function(){ return view('ajax'); });

The second route you need to create is the route that handles the ajax post request. Take notice that it is using the post method:

Route::post('/postajax','[email protected]');

2. The Controller Function

In the (second) route you created just now, the Controller function post in the AjaxController is called. So create the Controller

php artisan make:controller AjaxController

and in the app/Http/Controllers/AjaxController.php add the function post containing the following lines:

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;


class AjaxController extends Controller {

   public function post(Request $request){
      $response = array(
          'status' => 'success',
          'msg' => $request->message,
      );
      return response()->json($response); 
   }
}

The function is ready to receive data via a Http request and returns a json-formatted response (which consists of the status ‘success’ and the message the function got from the request).

3. The View

In the first step we defined the route pointing to the view ajax, so now create the view ajax.blade.php.

<!DOCTYPE html>
<html>
<head>

    <!-- load jQuery -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>

    <!-- provide the csrf token -->
    <meta name="csrf-token" content="{{ csrf_token() }}" />

    <script>
        $(document).ready(function(){
            var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
            $(".postbutton").click(function(){
                $.ajax({
                    /* the route pointing to the post function */
                    url: '/postajax',
                    type: 'POST',
                    /* send the csrf-token and the input to the controller */
                    data: {_token: CSRF_TOKEN, message:$(".getinfo").val()},
                    dataType: 'JSON',
                    /* remind that 'data' is the response of the AjaxController */
                    success: function (data) { 
                        $(".writeinfo").append(data.msg); 
                    }
                }); 
            });
       });    
    </script>

</head>

<body>
    <input class="getinfo"></input>
    <button class="postbutton">Post via ajax!</button>
    <div class="writeinfo"></div>   
</body>

</html>

If you wonder what’s the matter with this csrf-token, read https://laravel.com/docs/5.3/csrf

Leave a Comment