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. One of these functions is named ajax(). We can check the request type under controllers or route filters.

Allowing the request using route filters

Route filters provide a convenient way of limiting, accessing, or filtering the requests to a given route. There are several filters included in Laravel, which are located in the filters.php file in the app folder. We can define our custom filter under this file. We’ll not use this method in this chapter, but we’ll examine route filters in further chapters. The route filter for an Ajax request should be as shown in the following code:

Route::filter('ajax_check', function()
{
  if (Request::ajax())
    {
      return true;
    }
});

Attaching a filter to a route is also very easy. Check the sample route shown in the following code:

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

In the preceding example, we defined a route filter to the route with the before variable. This means, our application first checks the request type and then calls the controller function and passes the data.

Allowing the request using the controller side

We can check for the request type under controller. We’ll use this method in this section. This method is useful for function-based filtering. For doing this, we should change our add and update functions as shown in the following code:

public function postAdd() {
  if(Request::ajax()){
    $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) {
  if(Request::ajax()){
    $task = Todo::find($id);
    $task->title = Input::get("title");
    $task->save();
    return "OK"; 
  }

Wrapping up

In this chapter, we coded to add a new task, updated it, and listed the tasks. We also need to update each status and delete the tasks. For doing that, we need two functions that are called getDone() and getDelete(). As you know from previous sections of this chapter, these functions are RESTful and accept GET method requests. So, our function should be as shown in the following code:

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

We also need to update the todo.js file. The final JavaScript code should be as shown in the following code:

function task_done(id){
  $.get("/done/"+id, function(data) {
    if(data=="OK"){
      $("#"+id).addClass("done");
    }
  });
}
function delete_task(id){
  $.get("/delete/"+id, function(data) {
    if(data=="OK"){
      var target = $("#"+id);
      target.hide('slow', function(){ target.remove(); });
    }
  });
}
function show_form(form_id){
  $("form").hide();
  $('#'+form_id).show("slow");
}
function edit_task(id,title){
  $("#edit_task_id").val(id);
  $("#edit_task_title").val(title);
  show_form('edit_task');
}
$('#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");
  }
});
$('#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");
  }
});

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