Inserting data to the database with Ajax

In this application, we’ll use the Ajax POST method for inserting data to the database. jQuery is the best JavaScript framework for these kinds of applications. jQuery also comes with powerful selector functions.

We have two forms in our HTML code, so we need to post them with Ajax to insert or update the data. We’ll do it with jQuery’s post() method.

We’ll serve our JavaScript files under /public/assets/js, so let’s create a todo.js file under this directory. First we need a request to add new tasks. The JavaScript code contains the following code:

$('#add_task').submit(function(event) {
  /* stop form from submitting normally */
  event.preventDefault();
  var title = $('#task_title').val();
  if(title){
    //ajax post the form
    $.post("/add", {title: title}).done(function(data) {
      $('#add_task').hide("slow");
      $("#task_list").append(data);
    });
  }
  else{
    alert("Please give a title to task");
  }
});

This code posts our add_task form to the server if the user remembers to provide a title to the task. If the user forgets to provide a title to the task, the code does not post the form. After it is posted, the code will hide the form and append the task list with a new record. Meanwhile, we will be waiting for the response to get the data.

So we need a second form to update a task’s title. The code will update the task’s title and change the text of updated records via Ajax on-the-fly. On-the-fly programming (or live coding) is a style of programming in which the programmer/performer/composer augments and modifies the program while it is running, without stopping or restarting, in order to assert expressive, programmable control for performance, composition, and experimentation at runtime. Because of the fundamental powers of programming languages, we believe the technical and aesthetic aspects of on-the-fly programming are worth exploring in web applications. The update form’s code should be as follows:

$('#edit_task').submit(function(event) {
  /* stop form from submitting normally */
  event.preventDefault();
  var task_id = $('#edit_task_id').val();
  var title = $('#edit_task_title').val();
  var current_title = $("#span_"+task_id).text();
  var new_title = current_title.replace(current_title, title);
  if(title){
    //ajax post the form
    $.post("/update/"+task_id, {title: title}).done(function(data){
      $('#edit_task').hide("slow");
      $("#span_"+task_id).text(new_title);
    });
  }
  else{
    alert("Please give a title to task");
  }
});

Laravel has the RESTful controller feature. This means you can define the RESTful base of the routes and controller functions. Also, routes can be defined for different request types such as POST, GET, PUT, or DELETE.

 

Before defining the routes, we need to code our controller. The controller files stay under app/http/controllers/; create a file in it named TodoController.php. The controller code should be as follows:

<?php
class TodoController extends BaseController
{
  public $restful = true;
  public function postAdd() {
    $todo = new Todo();
    $todo->title = Input::get("title");
    $todo->save();      
    $last_todo = $todo->id;
    $todos = Todo::whereId($last_todo)->get();
    return View::make("ajaxData")->with("todos", $todos);
  }
  public function postUpdate($id) {        
    $task = Todo::find($id);
    $task->title = Input::get("title");
    $task->save();
    return "OK";        
  }
}

Let’s examine the code.

As you can see in the code, RESTful functions define syntaxes such as postFunction, getFunction, putFunction, or deleteFunction.

We have two post forms, so we need two POST functions and one GET method to get records from the database and show them in the template in the foreach statement to the visitor.

Let’s examine the postUpdate() method in the preceding code:

public function postUpdate($id) {
  $task = Todo::find($id);
  $task->title = Input::get("title");
  $task->save();
  return "OK";
}

The following points explain the preceding code:

  • The method needs a record called id to update. The route where we post would be similar to /update/record_id.
  • $task = Todo::find($id); is that part of the method which finds the record from the database which has the given id.
  • $task->title = Input::get("title"); means to get the value of the form element named title and updating the title column record as the posted value.
  • $task->save(); applies the changes and runs the update query on the database server.

Let’s examine the postAdd() method. This method works like our getIndex() method. The first part of the code creates a new record on the database server:

public function postAdd() {
  $todo = new Todo();
  $todo->title = Input::get("title");
  $todo->save();      
  $last_todo = $todo->id;
  $todos = Todo::whereId($last_todo)->get();
  return View::make("ajaxData")->with("todos", $todos);
}

The following points explain the preceding code:

  • The code line $last_todo = $todo->id; gets the ID of this record. It is equivalent to the mysql_insert_id() function.
  • The code line $todos = Todo::whereId($last_todo)->get(); fetches the record from the todo table which has an id column equal to $last_todo variable.
  • The code line View::make("ajaxData") ->with("todos", $todos); is very important to understand Laravel’s view mechanism:
    • The code line View::make("ajaxData") refers to our template file. Do you remember the ajaxData.blade.php file, which we created under /app/views/? The code calls this file.
    • The code line ->with("todos", $todos); assigns the last record to the template file as a variable named todos (the first parameter). So, we can show the last record in the template file with the foreach loop.

     

    Retrieving the list from the database

    We also need a method for getting the existing data from our database server. In our controller file, we need the function as shown in the following code:

    public function getIndex() {
      $todos = Todo::all();
      return View::make("index")
        ->with("todos", $todos);
    }

    Let’s examine the getIndex() method:

    • In the code, $todos = Todo:all() means to get all records from the database and assign them to the $todos variable.
    • In the code, View::make("index") defines our template file. Did you remember the index.blade.php file, which we created under /app/views/? The code calls this file.
    • In the code, ->with("todos", $todos); assigns the records to the template file. So, we can show the records in the template file with the foreach loop.

    Finally, we will define our routes. For defining routes, you should open the routes.php file in the apps folder. Laravel has a great feature for defining routes named the RESTful controller. You can define all the routes with a single line of code as follows:

    Route::controller('/', 'TodoController');

    The preceding code assigns all the applications’ root-based requests to the TodoController function. If you need to, you can also define the routes manually as follows:

    Route::method('path/{variable}', '[email protected]');