This question came up in a forum where I drop by now & then. It is also something that I recall answering previously on one or two occasions. So I thought I’d write about it here with a rudimentary example to provide a gist of how it works.
There’s no mystery or secret voodoo involved in having AJAX work in a Laravel app. On its own Laravel 4 (current version) doesn’t have any API for implementing AJAX, so you’ll need to do the footwork yourself. The basic concept that applies everywhere else applies here as well; grab the data from a HTML form, create an AJAX request and send it to server to a URL on which data is expected. Form data is retrieved on server just like any normal form data would be, the only key part is since you’re dealing with an AJAX request you can’t send back a normal View as response, you’ll need to make your own response with proper headers.
Note: I’ve assumed availability of jQuery in this example to avoid writing too much boilerplate. If you use any other library then you can use that as well, usage of jQuery is just to demonstrate the concept.
Lets add example routes to our routes.php
file:
- //Settings: show form to create settings
- Route::get( '/settings/new', array(
- 'as' => 'settings.new',
- 'uses' => 'SettingsController@add'
- ) );
- //Settings: create a new setting
- Route::post( '/settings', array(
- 'as' => 'settings.create',
- 'uses' => 'SettingsController@create'
- ) );
Then we create a view which has a form for adding a new setting:
- {{ Form::open( array(
- 'route' => 'settings.create',
- 'method' => 'post',
- 'id' => 'form-add-setting'
- ) ) }}
- {{ Form::label( 'setting_name', 'Setting Name:' ) }}
- {{ Form::text( 'setting_name', '', array(
- 'id' => 'setting_name',
- 'placeholder' => 'Enter Setting Name',
- 'maxlength' => 20,
- 'required' => true,
- ) ) }}
- {{ Form::label( 'setting_value', 'Setting Value:' ) }}
- {{ Form::text( 'setting_value', '', array(
- 'id' => 'setting_value',
- 'placeholder' => 'Enter Setting Value',
- 'maxlength' => 30,
- 'required' => true,
- ) ) }}
- {{ Form::submit( 'Add Setting', array(
- 'id' => 'btn-add-setting',
- ) ) }}
- {{ Form::close() }}
After this comes the Javascript which is loaded into our view which makes the AJAX call:
- jQuery( document ).ready( function( $ ) {
- $( '#form-add-setting' ).on( 'submit', function() {
- //.....
- //show some spinner etc to indicate operation in progress
- //.....
- $.post(
- $( this ).prop( 'action' ),
- {
- "_token": $( this ).find( 'input[name=_token]' ).val(),
- "setting_name": $( '#setting_name' ).val(),
- "setting_value": $( '#setting_value' ).val()
- },
- function( data ) {
- //do something with data/response returned by server
- },
- 'json'
- );
- //.....
- //do anything else you might want to do
- //.....
- //prevent the form from actually submitting in browser
- return false;
- } );
- } );
And now that Javascript and form UI are in place, its time to do the backend stuff in our controller:
- class SettingsController extends BaseController {
- /**
- * show a view with form to create settings
- */
- public function add() {
- return View::make( 'settings/new' );
- }
- /**
- * handle data posted by ajax request
- */
- public function create() {
- //check if its our form
- if ( Session::token() !== Input::get( '_token' ) ) {
- return Response::json( array(
- 'msg' => 'Unauthorized attempt to create setting'
- ) );
- }
- $setting_name = Input::get( 'setting_name' );
- $setting_value = Input::get( 'setting_value' );
- //.....
- //validate data
- //and then store it in DB
- //.....
- $response = array(
- 'status' => 'success',
- 'msg' => 'Setting created successfully',
- );
- return Response::json( $response );
- }
- //end of class
- }
As you can see, it is quite straightforward. You create a POST request to the URI with data and the controller method on server receives data as nomral form data. It then parses it, do with it whatever it wants and responds back with the header of content type application/json
(or it can be XML or any other data format) which the Javascript in browser is expecting.
Just the usual AJAX stuff. You can ofcourse find and use PHP/Javascript libraries which will do the heavy lifting for you so you can just make few API calls instead of writing your own Javascript boilerplate.
UPDATE: Updated the code example above to use Response::json()
instead of the custom function which created a Response
object and set the content type header to application/json
.