Creating an Ajax search function in laravel

If we want to search for information in our application, it might be useful to perform the search
asynchronously. That way, the user won’t have to be taken to a new page and have all the assets
refreshed. Using Laravel and JavaScript, we can perform this search in a very simple manner.
Getting ready
For this recipe, we’ll need a working installation of Laravel.
How to do it…
To complete this recipe, follow these steps:
1. In the controllers directory, create a file named SearchController.php:
<?php
class SearchController extends BaseController {
public function getIndex()
{
return View::make(‘search.index’);
}
public function postSearch()
{
$return = array();

$term = Input::get(‘term’);
$books = array(
array(‘name’ => ‘Alice in Wonderland’, ‘author’ => ‘Lewis
Carroll’),
array(‘name’ => ‘Tom Sawyer’, ‘author’ => ‘Mark
Twain’),
array(‘name’ => ‘Gulliver\’s Travels’, ‘author’ =>
‘Jonathan Swift’),
array(‘name’ => ‘The Art of War’, ‘author’ => ‘Sunzi’),
array(‘name’ => ‘Dracula’, ‘author’ => ‘Bram Stoker’),
array(‘name’ => ‘War and Peace’, ‘author’ =>
‘LeoTolstoy’),
);
foreach ($books as $book) {
if (stripos($book[‘name’], $term) !== FALSE) $return[] =
$book;
}
return Response::json($return);
}
}
2. In the routes.php file, register the controller:
Route::controller(‘search’, ‘SearchController’);
3. In the views directory, create a folder named search, and in that folder, create a file
named index.php:

<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>AJAX Search</title>
<script type=”text/javascript”
src=”//ajax.googleapis.com/ajax/libs/jquery/
1.9.0/jquery.min.js”></script>
</head>
<body>
<h1>Search</h1>
<form id=”search-form”>
<input name=”search” id=”term”> <input type=”submit”>
</form>
<div id=”results”></div>
<script>
$(function() {
$(“#search-form”).on(“submit”, function(e) {
e.preventDefault();

var search_term = $(“#term”).val();
var display_results = $(“#results”);
display_results.html(“loading…”);
var results = ”;
$.post(“search/search”, {term: search_term}, function(data)
{
if (data.length == 0) {
results = ‘No Results’;
} else {
$.each(data, function() {
results += this.name + ‘ by ‘ + this.author + ‘<br>’;
});
}
display_results.html(results);
});
})
});
</script>
</body>
</html>

How it works…

We first create a RESTful controller that holds two methods: one for our main page and one
to process the search. On our main page, we have a single text field and a submit button.
When the form is submitted, our JavaScript will post the form to our search page. If there are
results, it will loop through them and display them in our results div.
For our postSearch() method, we use an array as our data source. When a search is
posted, we then loop through the array to see if the string matches any of our titles. If so,
the value is added to an array and that array is returned as a JSON.

Leave a Reply

Your email address will not be published. Required fields are marked *