Laravel 5 Ajax Tutorial

Introduction

In the previous tutorial, we implemented the blog for Larashop. In this tutorial, we will cover the basics of Ajax and create a simple CRUD Laravel Ajax example. As a tutorial exercise, you will be required to use the knowledge you will gain to implement the commenting system for Larashop.

The tutorial will first cover the Ajax theory, discusses the advantages and disadvantages then show you how to do the implementation. If you are already familiar with the theory then you can skip it and go to the implementation.

Laravel Ajax CRUD

Topics to be covered

We will cover the following topics in this tutorial.

  • Tutorial Pre-requisites
  • What is Ajax
  • Why use Ajax?
  • When to Use Ajax
  • jQuery Ajax API
  • Laravel Ajax CRUD Example
  • Larashop Ajax Commenting System

Tutorial Pre-requisites

This tutorial assumes;

  • You understand the basics of Laravel
  • You have PHP, MySQL and Apache up and running
  • You have the basics of HTML and JavaScript especially jQuery
  • You have composer installed
  • You have a text editor or IDE that supports PHP.
  • You have a modern web browser that supports HTML5
  • You have been following the tutorial series and you understand the basics of Laravel 5.

What is Ajax?

Ajax is the acronym for Asynchronous JavaScript and XML. Ajax refers to a group of technologies that enable web application clients to send and receive data from the server asynchronously. In this case, asynchronous refers to sending and retrieving data in the background without affecting the display of the current page.

Ajax is implemented using the following technologies

  • JavaScript – client side scripting language that ties all of the technologies together
  • HTML/XHTML/CSS – used for the presentation of data
  • Document Object Model (DOM) – used to access and manipulate structured documents
  • XML / JSON – used to exchange data. JSON is now commonly used in place of XML format.
  • XMLHttpRequest – JavaScript object that is responsible for asynchronous communication with the server.

Advantages and disadvantages of Ajax?

The following are some of the advantages of Ajax when developing web applications.

  • Improved User Experience – Ajax makes it possible to create interactive applications that are fast and do not require reloading the whole page. The user can continue using the application whilst Ajax operations are going on in the background
  • Reduced bandwidth usage – Bandwidth costs money and Ajax enables you to save. Traditional applications require reloading all of the assets even if you are only interested in a small section of the application. This results in using up a lot of bandwidth. Ajax only lets you pull the required data from the server.
  • Improved system performance – Ajax only retrieves the required data from the server. This greatly improves the system performance and response time.
  • Promotes separation of data, business logic and presentation – Ajax calls usually retrieve data from the server and if necessary business logic is applied. Data is displayed after these actives have successfully been completed.

The following are the disadvantages if using Ajax

Requires JavaScript – JavaScript is a client-side technology and you have no control over it. If the user disables JavaScript on their web browser then Ajax will not work. • Web browser compatibility – not all web browsers especially very old ones have support for all of the technologies that Ajax uses. These days most browsers support these technologies so you should worry much about this. • Hard/impossible to bookmark content – users usually bookmark content so that they can easily go back to it later. With Ajax content, this is impossible or at a minimum requires extra effort to implement. • JavaScript Content generally isn’t SEO friendly – it is easier for Search Engines to crawl classic content compared to content that is generated via JavaScript. Developing SEO content with JavaScript requires extra efforts.

In conclusion, in most cases, the advantages outweigh the disadvantages and you will have to work with Ajax in one way or another. The next section looks at when you should use Ajax

When to Use Ajax

The following are some of the idea situations when you should use Ajax

  • Auto complete – if you have worked with any search engine, chances are suggestions were made to you before you could complete typing. Ajax can be used to provide such functionality
  • Auto save – when you are composing an email and something to your internet and you lose the connection to the server, chances are you will find your work in drafts directory. This is just one example. If you develop a content management system, you can also provide similar functionality where you save the users work periodic to provide auto restore functionality.
  • Pagination – you can only see so much at a time. Pagination allows you to display a limited number of items at a time and provide links that allow users to view the next segment. Google Search lists 10 items per page and provides you with links to other result pages. Ajax can greatly improve the user experience when displaying content that has been paginated.
  • Blog comments – what’s a blog without a comments section? The experience is improved when it is implemented using Ajax. Users can submit comments without reloading the entire page which can be very frustrating.
  • Real time validation – you can use Ajax to provide feedback to users in real time. Its say a user is filling in a registration form on website. You can use Ajax to validate the submitted email address and let the user know if it is available before the user even submits the form.
  • …and many more – Ajax can also be used to implement functionality such as surveys, online voting, filtering and sorting data etc.

jQuery Ajax API

Using Ajax requires you to know JavaScript and a set of other technologies. This increases the development time and cost. Fortunately, JavaScript libraries such as jQuery can make your life easier. jQuery has an Ajax API that provides Ajax implementation.

Laravel Ajax CRUD Example

Before we implement the blog commenting system for Larashop, we will first need to understand the basics of Ajax and Laravel. We will create a new project with functionality for creating, reading, updating and deleting data.

I am using Windows 8.1 and I have XAMPP installed on drive C so some of the commands will be more specific to my operating system Open the command prompt / terminal.

I will now browse to C:\xampp\htdocs

cd C:\xampp\htdocs

Run the following command to create a new project.

composer create-project laravel/laravel ajax-crud

HERE,

  • The above command create a directory ajax-crud in the htdocs directory and install Laravel

After the above command has run successfully, run the following command to browse to the new project directory

cd ajax-crud

Let’s now test the installation. We will work with the built in server.

Run the following command

php artisan serve

HERE,

  • The above command starts the build in web serve on port 8000

Open the following URL in your web browser

http://localhost:8000/

You will see the welcome page for Laravel

We will create a simple to do list application

Open the command prompt / terminal and browse to the project root.

Run the following command to create a model and migration file at the same time.

php artisan make:model Task –m

HERE,

  • The above command creates a model task and its migration file

Open the model Task in /app/Task.php

Update the code to the following

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Task extends Model
{
    protected $fillable = ['task', 'description','done'];
}

HERE,

  • protected $fillable = ['task', 'description','done']; specifies the fields that can be mass assigned.

Open the migration file in /database/migrations/xxxx_xx_xx_xxxxxx_create_tasks_table.php

Update the code to the following

<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
use App\Task;

class CreateTasksTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('tasks', function (Blueprint $table) {
            $table->increments('id');
            $table->string('task');
            $table->string('description');
            $table->boolean('done');
            $table->timestamps();
        });

        Task::create([
            'task' => 'Weekend hookup',
            'description' => 'Call Helga in the afternoon',
            'done' => false,
            ]);

        Task::create([
            'task' => 'Late night coding',
            'description' => 'Finishing coding POS API',
            'done' => false,
            ]);
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('tasks');
    }
}

If you are not familiar with the concepts of migrations then I recommend you read this tutorial Laravel Migrations Tutorial Before we run our migration files, we will need to create a database in MySQL and configure our project to connect to the database.

Run the following SQL statement in MySQL

Create schema ajax_crud;

Open .envfile in the project root.

Set the configurations as shown below

DB_HOST=localhost
DB_DATABASE=ajax_crud
DB_USERNAME=root
DB_PASSWORD=xxx

Note: the above settings should match the ones on your development machine.

Execute the following command to run the migrations

php artisan migrate 

Check the database after running the migration files. You should be able to see the tasks table with two records that we seeded in the migration file. We will use twitter bootstrap tables and modal forms. jQuery will provide us with Ajax implementation.

Open /resources/views/welcome.blade.php

Replace the default HTML code with the following

<!DOCTYPE html>
<html lang="en-US">
<head>
    <title>Laravel Ajax CRUD Example</title>

    <!-- Load Bootstrap CSS -->
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container-narrow">
        <h2>Laravel Ajax ToDo App</h2>
        <button id="btn-add" name="btn-add" class="btn btn-primary btn-xs">Add New Task</button>
        <div>

            <!-- Table-to-load-the-data Part -->
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Task</th>
                        <th>Description</th>
                        <th>Date Created</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody id="tasks-list" name="tasks-list">
                    @foreach ($tasks as $task)
                    <tr id="task{{$task->id}}">
                        <td>{{$task->id}}</td>
                        <td>{{$task->task}}</td>
                        <td>{{$task->description}}</td>
                        <td>{{$task->created_at}}</td>
                        <td>
                            <button class="btn btn-warning btn-xs btn-detail open-modal" value="{{$task->id}}">Edit</button>
                            <button class="btn btn-danger btn-xs btn-delete delete-task" value="{{$task->id}}">Delete</button>
                        </td>
                    </tr>
                    @endforeach
                </tbody>
            </table>
            <!-- End of Table-to-load-the-data Part -->
            <!-- Modal (Pop up when detail button clicked) -->
            <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
                <div class="modal-dialog">
                    <div class="modal-content">
                        <div class="modal-header">
                            <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
                            <h4 class="modal-title" id="myModalLabel">Task Editor</h4>
                        </div>
                        <div class="modal-body">
                            <form id="frmTasks" name="frmTasks" class="form-horizontal" novalidate="">

                                <div class="form-group error">
                                    <label for="inputTask" class="col-sm-3 control-label">Task</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control has-error" id="task" name="task" placeholder="Task" value="">
                                    </div>
                                </div>

                                <div class="form-group">
                                    <label for="inputEmail3" class="col-sm-3 control-label">Description</label>
                                    <div class="col-sm-9">
                                        <input type="text" class="form-control" id="description" name="description" placeholder="Description" value="">
                                    </div>
                                </div>
                            </form>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-primary" id="btn-save" value="add">Save changes</button>
                            <input type="hidden" id="task_id" name="task_id" value="0">
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <meta name="_token" content="{!! csrf_token() !!}" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
    <script src="{{asset('js/ajax-crud.js')}}"></script>
</body>
</html>

The above code loops through an array of tasks and displays them in a table. It also loads jQuery, Bootstrap and a custom JavaScript file ajax-crud.js.

Next create the file ajax-crud.js in the directory /public/js/ajax-crud.js

Add the following code

$(document).ready(function(){

    var url = "/ajax-crud/public/tasks";

    //display modal form for task editing
    $('.open-modal').click(function(){
        var task_id = $(this).val();

        $.get(url + '/' + task_id, function (data) {
            //success data
            console.log(data);
            $('#task_id').val(data.id);
            $('#task').val(data.task);
            $('#description').val(data.description);
            $('#btn-save').val("update");

            $('#myModal').modal('show');
        }) 
    });

    //display modal form for creating new task
    $('#btn-add').click(function(){
        $('#btn-save').val("add");
        $('#frmTasks').trigger("reset");
        $('#myModal').modal('show');
    });

    //delete task and remove it from list
    $('.delete-task').click(function(){
        var task_id = $(this).val();

        $.ajax({

            type: "DELETE",
            url: url + '/' + task_id,
            success: function (data) {
                console.log(data);

                $("#task" + task_id).remove();
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });

    //create new task / update existing task
    $("#btn-save").click(function (e) {
        $.ajaxSetup({
            headers: {
                'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
            }
        })

        e.preventDefault(); 

        var formData = {
            task: $('#task').val(),
            description: $('#description').val(),
        }

        //used to determine the http verb to use [add=POST], [update=PUT]
        var state = $('#btn-save').val();

        var type = "POST"; //for creating new resource
        var task_id = $('#task_id').val();;
        var my_url = url;

        if (state == "update"){
            type = "PUT"; //for updating existing resource
            my_url += '/' + task_id;
        }

        console.log(formData);

        $.ajax({

            type: type,
            url: my_url,
            data: formData,
            dataType: 'json',
            success: function (data) {
                console.log(data);

                var task = '<tr id="task' + data.id + '"><td>' + data.id + '</td><td>' + data.task + '</td><td>' + data.description + '</td><td>' + data.created_at + '</td>';
                task += '<td><button class="btn btn-warning btn-xs btn-detail open-modal" value="' + data.id + '">Edit</button>';
                task += '<button class="btn btn-danger btn-xs btn-delete delete-task" value="' + data.id + '">Delete</button></td></tr>';

                if (state == "add"){ //if user added a new record
                    $('#tasks-list').append(task);
                }else{ //if user updated an existing record

                    $("#task" + task_id).replaceWith( task );
                }

                $('#frmTasks').trigger("reset");

                $('#myModal').modal('hide')
            },
            error: function (data) {
                console.log('Error:', data);
            }
        });
    });
});

HERE,

  • var url = "/ajax-crud/public/tasks"; defines the URL that all Ajax calls will use. As a matter of personal preference, I use apache web server instead of the built in server. If you use the built in server then you don’t need to include /ajax-crud/public.
  • $('.open-modal').click(function(){…} defines the function that is called whenever an element with a class open-modal is clicked. This function display the modal form for editing a task
  • $('#btn-add').click(function(){…} this function opens the modal form for adding new tasks
  • $('.delete-task').click(function(){…} deletes a task from the database and removes it from the list
  • $("#btn-save").click(function (e) {…} this function creates a new task or updates an existing task.

That was it for the client side. We will now need to create a basic API that will be responding to our Ajax calls. For the sake of simplicity, we will use anonymous functions in the routes file. We will not create any controller.

Open /app/Http/routes.php

Add the following routes

Route::get('/tasks/{task_id?}',function($task_id){
    $task = Task::find($task_id);

    return Response::json($task);
});

Route::post('/tasks',function(Request $request){
    $task = Task::create($request->all());

    return Response::json($task);
});

Route::put('/tasks/{task_id?}',function(Request $request,$task_id){
    $task = Task::find($task_id);

    $task->task = $request->task;
    $task->description = $request->description;

    $task->save();

    return Response::json($task);
});

Route::delete('/tasks/{task_id?}',function($task_id){
    $task = Task::destroy($task_id);

    return Response::json($task);
});

The above code interacts with the task model and returns the response in json format.

Replace the root route with the following code

Route::get('/', function () {
    $tasks = Task::all();

    return View::make('welcome')->with('tasks',$tasks);
});

The above code retrieves all of the tasks from the tasks table and passes them to the view welcome

Load the following URL in your web browser

http://localhost/ajax-crud/public/

You will get the following results

Laravel Ajax CRUD

Click on edit button

You will get a modal form with the details of the task that you clicked

Laravel Ajax CRUD

Larashop Ajax commenting system

Using the concepts that you have learnt in this tutorial, implement the commenting system for Larashop. You can share your code with others if you would like to. If you are stuck, use the comments section to ask for help.

What’s next?

The commenting system for Larashop will eventually be implemented and the tutorial will be posted but we first need to clean up for code. We are currently refactoring the code for Larashop and updating all of the existing tutorials. New tutorials will be posted after the cleanup exercise is done.

If you found this tutorial useful, support us by using the social media buttons to like and share the tutorial. If you didn’t find it useful, please use the comments section below to let us know how we can do better next time.

Each week, a new Laravel tutorial is added to our collection. Subscribe to our newsletter, like our Facebook fan page or follow us on Twitter to get free updates when the collection is updated.

Tutorial History

Tutorial version 1: Date Published 2016-01-18

Related Tutorials