Skip to main content
Image for post: Laravel 5 Form Ajax Post

Laravel 5 Form Ajax Post

This was harder than I thought. Here is my approach and my solution. I've used JQuery and follwed the instructions on the Laravel documentation to solve the token detection problem after the form posts and display the result in a div. Here is my code: On the main page add this html meta tag:


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

Controller



namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;

class AjaxPostController extends Controller
{
   /**
    * Render a form to perform an ajax post
    *
    * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
    */
   public function index()
   {
       return view('formajax.form_ajax_post');
   }

   /**
    * Receive the ajax POST request from the form
    *
    * @param Request $request
    * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
    */
   public function ajaxpost(Request $request)
   {
       return view('formajax.form_ajax_post_response', ['request' => $request->all()]);
   }
}

Views

I have an app.blade.php view with the classic title, content and footer sections. You can extract the code you want from all these examples. form_ajax_post.blade.php:



@extends('app')

@section('title')
   Form Ajax POST
@stop

@section('content')

   <h3>Form Ajax post</h3>

   <p>Perform an Ajax POST request and displaying the result in a div with JQuery</p>

   {!! Form::open(['method' => 'post', 'action' => 'AjaxPostController@ajaxpost', 'id' => 'frmajaxpost', 'role' => 'form']) !!}
   <div class="form-group">
       {!! Form::label('name', 'Name:') !!}
       {!! Form::text('name', null, ['class' => 'form-control', 'title' => '', 'required' => 'required']) !!}
   </div>

   <div class="form-group">
       {!! Form::label('categories', 'Categories:') !!}
       {!! Form::select('categories', ['default' => 'Select', 1 => 'Apples', 2 => 'Pears', 3 => 'Oranges'], null, ['class' => 'form-control', 'title' => '']) !!}
   </div>

   <div class="form-group">
       {!! Form::label('sex', 'Sex:') !!}
       {!! Form::radio('sex', 'male', true) !!} Male {!! Form::radio('sex', 'female') !!} Female
   </div>

   <div class="form-group">
       {!! Form::label('categories', 'Choose:') !!}
       {!! Form::checkbox('choosecheck[]', 'something', false, ['id' => 'something']) !!} <label for="something" style="font-weight: normal;">Something</label>
       {!! Form::checkbox('choosecheck[]', 'somethingelse', false, ['id' => 'somethingelse']) !!} <label for="somethingelse" style="font-weight: normal;">Something else</label>
   </div>

   <div class="form-group">
       {!! Form::submit('Proceed', ['class' => 'btn btn-primary form-control']) !!}
   </div>
   {!! Form::close() !!}

   <div id="result"></div>

   @include('common.forms._form_error_messages')
@stop

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

       var validate = $("#frmajaxpost").validate({
           submitHandler: performAjaxSubmit()
       });

       function performAjaxSubmit()
       {
           $("#frmajaxpost").submit(function(event) {
               event.preventDefault();

               $.ajax({
                   type     : "POST",
                   url      : $(this).attr('action'),
                   data     : $(this).serialize(),
                   cache    : false,

                   success  : function(data) {
                       $( "#result" ).empty().append( data );
                   }
               });

               return false;
           });
       }

   </script>
@stop

form_ajax_post_response.blade.php



<h3>POST result:</h3>
<p><strong>Name:</strong> {{ $request['name'] }}</p>
<p><strong>Category:</strong> {{ $request['categories'] }}</p>
<p><strong>Sex:</strong> {{ $request['sex'] }}</p>

@if(isset($request['choosecheck']))
   <p><strong>Checkbox:</strong> {{ dump($request['choosecheck']) }}</p>
@endif

So this is only an example. Be sure your main view sees JQuery. Happy coding!

Share this post

This website and/or any sub domains use cookies to understand how you to improve your experience.