CodeIgniter and jQuery – Real Live Search with Pagination

In this tutorial, we will create a search page with CodeIgniter and jQuery. We’re not gonna create only a default search page using CodeIgniter framework, but also a real time search with jQuery’s support. And one more, enable GET method in CodeIginter that was stupidly disable by default. Enjoy the tut and don’t forget the … beer!

You can take a look at the demo or download it right now, then close this page immediately if you want to. But I highly recommend that you should read the whole tutorial, so you will not miss any interesting in this entry.

1. The stuffs I’m using

2. Configuring CodeIgniter

At first, download CodeIgniter (CI) with the link above and extract package to your workspace. Note, your web site will be located in CodeIginiter folder by default. Then, you need to make some changes to Codeiginter within the CI config section. In this tutorial, we’re using PHP to connect to MySQL database to get data.

Open the system/application/config/autoload.php, find the following code:

Because we’re gonna use Database to store and fetch from, so we load the database library. That’s all what it means. And each time you run your web page, it will automatically load the database connection.

The second, open up database.php in the same folder then find following code and change it to your database setting.

The next important part in CI Configuration is you have to config you default url of your website. This is a base url inside config.php file.
Open this file in then find and edit your base_url as below:

2. Database

Wow, it’s a large database file size if you build a search engineer. So, I will use my old WordPress database and the search will fetch data from my posts table. If you are setting up a search for a series of articles or a site with lots of product-related content, a MySQL FULLTEXT search can make it very easy to find articles or products related to the keywords used by a searcher. Read this entry to know more about FULLTEXT

.

Add FULLTEXT to the data fileds you want to index. In this tutorial, I will search through table wp_post and the result will be based on the search term within post_title and post_content fileds.

Of course, we only need the posts with status is published because wordpress stores a lot of posts in the table for revision.
Next, create a function that will calculate the total of rows, we need that number for pagination.

Because FULLTEXT will find the results by each word in the search phrase, so we need to split our search phrase first. This function will split the keyword into parts then highlight each word in the result.

Furthermore, you need a function that clean up the HTML format for displaying. The purpose of this function I will talk later in jQuery part.

5.Building the Controller

Now go to system/application/controllers and create a new file. Name this file as search.php. After create the file, the first thing we must do with this file is create a constructor which loads the model of search. Our search model is sear_modelthat we already created above.

Here is the most important part for our search. Because we will create 2 search methods which are default HTTP request and ajax request; therefore, we have to create a function that identifies each other request is.

Put this line into your index() method. Now, continue working with the index() by separating each method request. We will process the default HTTP Request first. For displaying, we need 4 files. Actually, we just want to create 3 files: search.php, search_form.php and search_result.php. However, we need to separate the search.php into search_header.php and search_footer.php to make it easier to edit later.

search_header.php: Header HTML goes here

search_form.php: Form search

search_result.php: Even when it has results or not, you need to display here

search_footer.php: HTML for footer goes here

We’re gonna make a default search page when have no request (It means no one submits search query). It’ll load the default view and pass variable search_term to search form. It’s anÂ empty value, but without it, your form will get error.

We don’t need to display the results in the default search page because it doesn’t have any result, right?
Inside the condition block when it has GET value of query, we will process the default HTTP request method here.

You maybe knew the easiest way to do pagination in CodeIginter suchs by using Pagination class, take a look at the CI Pagination Guide. However, it’s not as they said. It’s hard to customize, you need to write another pagination class to fit your needs. That’s why I don’t like it. The following code to paginate the result is just a simple code. Because we’ve talked about that over forum to forum. Please change it to your one pagination. Thank you!

We are passing all variables to the $data array to display it in view.

Now, we are on the topic of this entry. Build a ajax live search with jQuery and CodeIgniter. The code is similar to default HTTP request but may varies a little bit which is the results. The results in ajax respond are different. In this tutorial, I will make ajax response in JSON format.

A little bit thing but helpful to understand how is this form gonna get the result. It’s JSON format. The well-formatted JSON in this tutorial is:

The values in array paging is used for pagination. The start_idx and end_idx are the values that shows us the range in total of posts displayed in current page. The has_next and has_prev are boolean values that the next and previous button depend on. Here below is the ajax part:

When you display the results as JSON format, you need to make sure your data is cleaned up. Because some HTML tags will break the JSON format, then your jQuery code can not read it. That’s why I created a function to clean up HTML format earlier.

6. The View – Display your works

100% percent of people who are viewing the tut have already click to check the demo before reading, right? So, the demo you saw at the top of this entry is the result of all code below.

The search_header.php file: link to your css file and jQuery library, do some javascripts for the form, that’s all!

The CSS code is in the download file. It’s a very long code of CSS, so I decided not to post it here.

7. Work with jQuery

We need to use jquery to send request and display the data responded. Create javascript file name search.js in the js folder. Of course, this js folder is at root folder, not in views folder of Codeigniter. You can see the clear link of this file at the header which was created earlier.
The jQuery code was modified from the Knowledge Base of Mediatemple. I removed some unnecessary and complicated code. If we’re gonna make a live search, we’ll only need as enough as in this tutorial.

@Marek Stasikowski No, I did not ??? I just wrote a function to highlight the keywords! And to highlight them, of course, you have to have a html tags.
Uhm, let me think. Maybe writing this function with parameter is HTML is better.
Thanks

when I type the word “code” in the search box and let the ajax run the search rather than hitting Enter it display 1 to 5 of 38 so I scroll down and click Next and then I scroll down and click Next again but this second time the page reloads and I’m back to the start again. If I hit Enter though I get to go through all the other search results using the 1, 2, 3, 4 Prev, Next…..

Yeah, could be useful, just remember not to over-extend your fancy stuff with options
And sorry, I made a mistake; you stated you should write it in your controller, but still the header for that part of the post is called: “4. Building the Model” – hence the mistake.

After all, I still think HTML should only be present in the View layer, and there only.

@Killian: yes, I was really surprised
@amnesia7: It caused by number of characters to display. Sometime, you content will break line; and JSON format will be brake by the line break. Just change from 100 to 50 displayed character, it’s ok now.
@Marek Stasikowski: Thanks for your comments. And this is not my idea. I saw it on Mediatemple, and I want to write some code for the tutorial :D. Thanks!

$offset=($current_page-1)*$post_per_page;
if($current_page==1) {
$offset = 0;
}
if statement and assignment in it is completely useless because on page 1 result of offset will be 0 (1-1=0, 0 * some = 0). No need to assign it to 0 again.

I’m trying to append your code to this table
CREATE TABLE IF NOT EXISTS `notes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(25500) NOT NULL,
`unique_id` varchar(255) NOT NULL,
`create_date` datetime NOT NULL,
`lastChangeDate` datetime NOT NULL,
`content` longtext NOT NULL,
PRIMARY KEY (`id`),
FULLTEXT KEY `note_content` (`content`),
FULLTEXT KEY `title` (`title`,`content`),
FULLTEXT KEY `yarpp_content` (`content`),
FULLTEXT KEY `yarpp_title` (`title`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=391 ;
so I can search my notes that I store in a database. I can’t figure out why I’m not getting results returned. I went in to the code and replace all the post with notes and modified all sql so it not using wp_posts. Any help would be help great

wonderful post! i downloaded your tut n configured everything with codeigniter.. but prob comes up with search results… nothing happens! but if i remove post_content column from your select query at both places then 1 record comes when i search for ‘code’. for other keywords nothing happens.. please help or do u have any suggestions..?

The following is my .htacces file. (Its in the root folder live_search)

RewriteEngine On
RewriteBase /

#Removes access to the system folder by users.
#Additionally this will allow you to create a System.php controller,
#previously this would not have been possible.
#’system’ can be replaced if you have renamed your system folder.
RewriteCond %{REQUEST_URI} ^system.*
RewriteRule ^(.*)$ http://localhost/live_search/search/$1 [L]

#Checks to see if the user is attempting to access a valid file,
#such as an image or css document, if this isn’t true it sends the
#request to index.php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ http://localhost/live_search/search/$1 [L]

I’m using WAMP server. Am I missing any php extentions for things to work?

Maybe you are getting problem with the Full text search. Have you tried to do with normal search query? Actually, I don’t support this tutorial anymore, but I will take a look at the code again, and update it as soon as possible.

Oh I did move to another hosting provider! So I think it’s fine To someone cannot see the demo works: the database server is not configured correct after I changed hosting, but the source works. Thanks!

Hello Lam,
Thanks for your article,is very helpfull for learning Code ignitor, because the official documentation is poor of this light framework.
Please fix the demo online.
I’am unable to run the demo, i pasted the files, changed configuration file database.php and config.php and when i call to the controller search, example:

http://localhost/search
My CPU goes to 100% and never displays something, probable there is a loop.Anyways the tutorial is interesting.
Regards