Skip to content

Server generated JavaScript Responses

Tortue Torche edited this page Jul 21, 2014 · 25 revisions

with Laravel and Larasset

TL;DR

You can get a demo application HERE.

Prerequisites

You must install Node.js on your computer (development environment only).

Larasset package is only compatible with PHP >= 5.4 and Laravel >= 4.1 framework.

Installation

  1. So just make a new app
```sh
composer create-project laravel/laravel laravel_larasset_app --prefer-dist
```

1. Go inside your new app path

    ```sh
    cd laravel_larasset_app
    ```
  1. Then install Larasset package
Click [HERE](https://github.com/efficiently/larasset/blob/master/README.md#installation) to follow the installation instructions of this package.
  1. Configure your application database, for this tutorial we use SQLite

So you need to enable php_sqlite3 and php_pdo_sqlite extensions in your php.ini file.

In app/config/database.php

  'default' => 'sqlite',
  1. Create a Message resource

    1. To create the messages table we will use artisan, We hope you know how to use it.

      Let's init the migrate system and tell artisan to setup a user table. We are using additional parameters --table and --create, this way artisan builds a base class we can use.

      Console:

      php artisan migrate:make create_messages_table --table=messages --create

      You can find the php file artisan has created under app/database/migrations. The name of file depends on the date and time when it was created.

      Let's define a migration that looks like this:

      <?php
      //app/database/migrations/........_create_messages_table.php:
      
      use Illuminate\Database\Schema\Blueprint;
      use Illuminate\Database\Migrations\Migration;
      
      class CreateMessagesTable extends Migration {
      
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
          Schema::create('messages', function(Blueprint $table) {
        	$table->increments('id');
        	$table->string('title');
        	$table->text('body');
        	$table->timestamps();
          });
        }
      
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
          Schema::drop('messages');
        }
      
      }
    2. Next, we can run our migrations from our terminal using the migrate command. Simply execute this command from the root of your project:

      php artisan migrate
    3. Init some rendering methods and set a default layout for the controllers

      In your app/controllers/BaseController.php file:

      class BaseController extends \Controller
      {
      	use Efficiently\JqueryLaravel\ControllerAdditions;
      	
      	/**
      	 * The layout that should be used for responses.
      	 */
      	protected $layout = 'layouts.application';
      	
      	//code...
      }
    4. Then create the Message resource

      php artisan controller:make MessagesController

      Now we can register a resourceful route to the controller, add the line below a the end of app/routes.php file:

      Route::resource('messages', 'MessagesController');
    5. You will also need to create Message model, in app/models/Message.php

      <?php
      
      class Message extends \Eloquent
      {
      	protected $fillable = ['title', 'body'];
      
      }
3. Create the views of `Message`

	Views live in the `app/views` directory and contain the HTML of your application.

	1. We need to create a layout for these views `layouts/application.blade.php`

		Let's create our main layout for this application, `app/views/layouts/application.blade.php` file:
		
		```html
		<html>
			<head>
				<title>Laravel and Larasset Quickstart</title>
				{{ javascript_include_tag('application') }}
			</head>
			<body>        
				@yield('content')
			</body>
		</html>
		```

	1. Create the `app/views/messages/_message.blade.php` partial

		```html
		@div_for($message)
		    <p>
		        <strong>Title:</strong>
		        {{{ $message->title }}}
		    </p>
		    <p>
		        <strong>Body:</strong>
		        {{ nl2br(e($message->body)) }}
		    </p>
		@end_div_for
		```

	2. Create the `app/views/messages/show.blade.php` view

		```html
		@section('content')
		    @include('messages._message')
		@stop
		```

	3. Create the `app/views/messages/index.blade.php` view

		```html
		@section('content')
		    <h1>All messages:</h1>
		    <div id="messages">
		        {{-- renders app/views/messages/_message.blade.php for each message --}}
		        @foreach ($messages as $message)
		            @include('messages._message')
		        @endforeach
		    </div>
		
		    <h2>Add a message</h2>
		    <?php $message = App::make('Message'); ?>
		    @include('messages/_form')
		@stop
		```

	4. Create the `app/views/messages/_form.blade.php` view
		
		Form submitting via Ajax, with the help of the `data-remote` HTML attribute.

		```html
		{{ form_for($message, ['route' => 'messages.store', 'data-remote' => true]) }}   
			<div class="field">
				{{ Form::label('title') }}
				{{ Form::text('title') }}
			</div>
			<div class="field">
				{{ Form::label('body') }}
				{{ Form::textarea('body') }}
			</div>
			<div class="actions">
				{{ Form::submit('Send message') }}
			</div>
		{{ form_for_close() }}
		```

	5. Create the `app/views/messages/create.blade.php` view
	
		```html
		@section('content')
		    <?php $message = App::make('Message'); ?>
		    @include('messages._form')
		@stop
		```
		
	6. In your `app/controllers/MessagesController.php` file
		
		Server stores the model object.
		
		```php
		<?php

		class MessagesController extends \BaseController
		{
		
			/**
			 * Display a listing of the resource.
			 *
			 * @return Response
			 */
			public function index()
			{
				$messages = Message::all();
				
				return $this->render('messages.index', compact('messages'));
			}
		
		
			/**
			 * Show the form for creating a new resource.
			 *
			 * @return Response
			 */
			public function create()
			{
				return $this->render('messages.create');
			}
		
		
			/**
			 * Store a newly created resource in storage.
			 *
			 * @return Response
			 */
			public function store()
			{
				$message = \App::make('Message');
				$message->fill(\Input::except('_method', '_token'));
		
				if ($message->save()) {
					$format = \Request::format();
		
					switch ($format) {
						case 'html':
							// No js fallback
							$render = \Redirect::route('messages.show', $message->id);
							break;
						case 'js':
							// Just renders messages/store_js.blade.php
							$render = $this->render(['js' => 'messages.store'], ['message' => $message]);
							break;
						default:
							$render = \Redirect::route('home')->with('message', "Error: Unknown request");
							break;
					}
		
					return $render;
				}
		
				return \Redirect::route('home')->with('message', "Error: Unable to save the message");
			}
		
		
			/**
			 * Display the specified resource.
			 *
			 * @param  int  $id
			 * @return Response
			 */
			public function show($id)
			{
				$message = Message::findOrFail($id);
				
				return $this->render('messages.show', compact('message'));
			}

		//...
		```

	7. Create the file `app/views/messages/store_js.blade.php`

		Server generates a JavaScript response with the HTML embedded.
		
		```html
		// <script type="text/javascript"> {{-- Keep this line to have syntax highlight in IDE --}}

		$('#messages').append({{ json_encode(render_view('messages/_message', ['message' => $message])) }});// Add the new message
		$('#{{{ dom_id($message) }}}').fadeTo('slow', 0.2).fadeTo('fast', 1); // Add effects to highlight the new message
		$('#create_message').trigger("reset"); // Clear form fields

		// </script>{{-- Keep this line to have syntax highlight in IDE --}}
		```
		
		The final step of evaluating the response is automatically handled by the XMLHttpRequest-powered form generated by form_for,
		and the view is thus updated with the new message and that new message is then highlighted via a JS/CSS animation.
	8. Run your Laravel application and the assets servers

		```sh
		php artisan server
		```
		Then open this URL in your Web browser:
		[http://localhost:8000/messages](http://localhost:8000/messages)

Other Resources

External docs

jQuery UJS Wiki docs.

Credits

The Ruby on Rails framework.

jQuery Rails and jQuery UJS repositories.

And this excellent article about Server generated JavaScript Responses.

Clone this wiki locally