KodeInfo | Learning resources for web and mobile development

Building A To Do List with Ajax Using Laravel 4 - Part II

January 9th, 2015 11:37:10 by Imran Iqbal Comments(0) - Views(694)
Tags :

In this continuation tutorial we are going to see how we can save the tasks to the database using Ajax, listing all the tasks from database to the user and how to allow only Ajax based requests instead of all types of HTTP requests form user. let's continue where we left in the previous tutorial in building a to do list with Ajax using Laravel 4.

Inserting data to the database with Ajax

In this application, we will use the Ajax POST method for inserting data to the database. jQuery is the best javascript framework for these kinds of applications. 

We have two forms in our view file, so we need to post them with Ajax to insert or update the data. We will do it with jQuery's post() method.

$('#add_task').submit(function(event){

	/* Stop form 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");
	}

});

$('#edit_task').submit(function(event){

	/* Stop form submitting normally */
	event.preventDefault();

	var task_id = $('#edi_task_id').val();
	var title = $('#edit_task_title').val();
	var current_title = $('#title_'+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');
			$('#title_'+task_id).text(new_title);
		});
	}else{
		alert("Please give a title to task");
	}

});

Laravel has the RESTFul controller feature. This means we 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 our routes, we need to define our controller. The controller files stay under app/controllers/. Let's create a file in it named as TaskController.php. The controller should be as follows.

<?php
class TaskController extends BaseController
{
	public $restful = true;

	public function postAdd() {
		
		if(Request::ajax()){
			$task = new Task();
			$task->title = Input::get("title");
			$task->save();
			$last_task = $task->id;
			$tasks = task::whereId($last_task)->get();
			return View::make("ajaxData")->with("tasks", $tasks);
		}
	}

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

Let's look into the controller code. As we can see 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 users.

Let's look into the postUpdate() method in the above code.

The method needs a record called id to update. The route where we post would be similar to /update/record_id.


$task = Task::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.

The code line $last_task = $task->id; gets the ID of this record. It is equivalent to the mysql_insert_id() function.

The code line $tasks = Task::whereId($last_task)->get(); fetches the record from the task table which has an id column equal to $last_task variable.

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() {
		$tasks = Task::all();
		return View::make("index")->with("tasks", $tasks);
	}

The code line $tasks = Task::all() means to get all records from the database and assign them to the $tasks variable.

The code line View::make('index')->with('tasks','$tasks); defines our template file and also we are sending the data in an array format to the view file.

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

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

How to allow only Ajax requests

Our application accepts all POST and GET requests even without Ajax. But we just need to allow an Ajax request for add and update functions. Laravel's request class provides many methods for examining the HTTP request for your applications. Once of these functions is named ajax(). We can check the request type under controllers or route filters.

Route::filter('ajax_check', function()
{
       if (Request::ajax())
      {
         return true;
      }
});
Route::get('/add', array('before' => 'ajax_check', function()
{
        return 'The Request is AJAX!';
}));

We can check the request type under controller functions like following:

public function postAdd() {
		
		if(Request::ajax()){
			$task = new Task();
			$task->title = Input::get("title");
			$task->save();
			$last_task = $task->id;
			$tasks = task::whereId($last_task)->get();
			return View::make("ajaxData")->with("tasks", $tasks);
		}
	}

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

We have done till now adding a task, listing a task and updating a task. We also need to update each task status and delete all the tasks. For doing this, we need two functions that are called getDone() and getDelete()

public function getDelete($id) {
		
		if(Request::ajax()){
			$task = Task::whereId($id)->first();
			$task->delete();
			return "OK";
		}
	}
	public function getDone($id) {
		
		if(Request::ajax()){
			$task = Task::find($id);
			$task->status = 1;
			$task->save();
			return "OK";
		}
	}

In this application development we tried to understand how to use Ajax with Laravel. Throughout the tutorial series, we used the basics of templating, request filtering, routing, and RESTFul controllers. We also learned to update and delete data from our database.

Thanks

Kode Info

Author

  • Imran Iqbal
    Imran Iqbal

    Imran is a web developer and consultant from India. He is the founder of KodeInfo, the PHP and Laravel Community . In the meantime he follows other projects, works as a freelance backend consultant for PHP applications and studies IT Engineering . He loves to learn new things, not only about PHP or development but everything.

Related

WHY USE A FRAMEWORK OVER PLAIN PHP

WHY USE A FRAMEWORK OVER PLAIN PHP
read more

GETTING STARTED WITH LARAVEL

GETTING STARTED WITH LARAVEL
read more

UNDERSTANDING LARAVEL STRUCTURE

UNDERSTANDING LARAVEL STRUCTURE
read more

UNDERSTANDING LARAVEL ROUTES

UNDERSTANDING LARAVEL ROUTES
read more

comments powered by Disqus