Skip to content
World Wide Web Server edited this page Jul 4, 2012 · 18 revisions

jQuery is one of, if not the most popular JavaScript library available. I was surprised to not find any helpers for it for CodeIgniter. So, I decided to write my own and contribute back to the CI community.

Setup:

Place jquery_helper.php in your application/helpers/ folder.

You'll also need these asset files (or your own local copies):

    http://jqueryui.com/latest/themes/base/ui.all.css
    http://code.jquery.com/jquery-latest.js
    http://jqueryui.com/latest/ui/ui.core.js
    http://jqueryui.com/latest/ui/ui.draggable.js
    http://jqueryui.com/latest/ui/ui.droppable.js
    http://jqueryui.com/latest/ui/ui.resizable.js
    http://jqueryui.com/latest/ui/ui.dialog.js

Note: I developed this helper using jQuery 1.3.1

(Optional) If you want to use autocomplete input with Ajax you need to:

  1. Place autocomplete.php in your application/hooks/ folder.
  2. Edit your application/config/hooks.php and add: $hook['pre_system'][] = array( 'class' => 'Autocomplete', 'function' => 'override_get', 'filename' => 'autocomplete.php', 'filepath' => 'hooks', 'params' => array() );
  3. Download jQuery Autocomplete plugin: http://bassistance.de/jquery-plugins/jquery-plugin-autocomplete/
  4. Setup these asset files on your server: /path/to/your/jquery.autocomplete.css /path/to/your/local/jquery.autocomplete.min.js

Note: You can still use autocomplete inputs by statically passing an array of data by just doing steps 3 & 4 if you don't want to use the hook.

How to use the jquery helper:

A) Either add 'jquery' to autoload or in your controller class call $this->load->helper('jquery');

B) In your views use the jquery helper functions. Most are wrappers on top of form helper functions.

For example, you may have a view with a form for searching stories on Digg.  You want the user to enter in a 
search term, click submit on the form and have the results appear in a submodal dialog box:

search_form.php view:

<p>Search for Digg stories:</p>
<div class="search-form">
    &lt;?=ajax_form_open('diggsearch/search_digg', array('id'=>'formDiggSearch'))?&gt;
        <div>
            &lt;?=form_input('searchbox',$searchbox,'maxlength="40" size="40"'))?&gt;
            &nbsp;
            &lt;input id="searchBtn" type="submit" name="search" value="Search" /&gt;&lt;br/>
            (Enter in terms to find story title matches)
        </div>
    &lt;?=ajax_form_close()?&gt;
    &lt;?=simple_callback_dialog('formDiggSearch', array('modal'=>true,'height'=>400,'width'=>580))?&gt;
</div>
    
Then you just need to process the POST in your controller (ex. Diggsearch->search_digg()) as you would for a normal POST
and load the results view. For instance: 


function search_digg() {
    ini_set('user_agent', 'SampleCIjQueryHelperApp/1.0');
    $data['searchbox']=$this->input->post('searchbox', true);
    $diggApiResponse = file_get_contents&#40;"http://services.digg.com/search/stories?query=". urlencode($data['searchbox']&#41;."&appkey=http://example.com&type=json");
    $stories = json_decode($diggApiResponse);
    $this->load->view('diggsearch/search_results',$stories);
}
// update the app key to your domain.  example.com won't work.

Similarly, you may have an anchor that when the user clicks it, you want to slide down the search form:

index.php view snippet:
<div style="margin-left:20%;width:800px;">
    <h1>Search Digg Sample CodeIgniter WebApp using jQuery Helper</h1>
    <div style="float:right;">
        &lt;?=ajax_get_anchor('diggsearch/search_form','Search Digg', array('id'=>'search_anchor'))?&gt;
    </div>
    <div class="cb"></div>
    &lt;?=simple_callback_div('search_anchor', 'slideDown(1000)', array('style'=>'float:right;'))?&gt;
    <p>
        This is a sample Digg Search application that uses my jquery ajax helper for CodeIgniter.
        <br/><br/>
        Click the "Search Digg" link to the right to view the search form.
    </p>
</div>

C) Ajax autocomplete input:

You need to write a controller method that will output the return data one per line. I find the best way is to 
get a single dimension array variable with your data and then:

    echo implode("\n",$singleDimensionalArray);
    
The autocomplete pre_system hook is required because the autocomplete plugin passes 3 query parameters in its 
GET request:  "q", "limit", and "timestamp".  The hook will detect these and clear the query string and put them in
the POST.  So in your controller method you can access those 3 params like form data to do your processing (to query 
yor db or whatever) to populate your single dimensional array.  The autocomplete plugin can handle more complex 
scenarios but this helper function is only for the base use case.


Back to the example of the topic search form.  Say you want to suggest topics as the user is typing in the searchbox input.
You'll need to make this change to your search.php view:


<p>Search for Digg stories:</p>
<div class="search-form">
    &lt;?=ajax_form_open('diggsearch/search_digg', array('id'=>'formDiggSearch'))?&gt;
        <div>
            &lt;?=ac_form_input('searchbox',$searchbox,'maxlength="40" size="40"', 'diggsearch/suggest', array('max'=>5,'min'=>3))?&gt;
            &nbsp;
            &lt;input id="searchBtn" type="submit" name="search" value="Search" /&gt;&lt;br/>
            (Enter in terms to find story title matches)
        </div>
    &lt;?=ajax_form_close()?&gt;
    &lt;?=simple_callback_dialog('formDiggSearch', array('modal'=>true,'height'=>400,'width'=>580))?&gt;
</div>    

Then you will need to create a Diggsearch->suggest() method that returns the matches one per line:

function suggest() {
    ini_set('user_agent', 'SampleCIjQueryHelperApp/1.0');
    $diggApiResponse = file_get_contents&#40;"http://services.digg.com/search/stories?query=". urlencode($this->input->post('q', true&#41;)."&appkey=http://example.com&type=json");
    $stories = json_decode($diggApiResponse);
    $suggestions = array();
    for($i=0;$i<$this->input->post('limit', true); $i++) {
        $suggestions[] = $stories->stories[$i]->title;
    }
    echo implode("\n", $suggestions);
}  

Note: You need to change the app key to your domain.  example.com will not work.  Also don't abuse the Digg api.  You can get your IP banned. 
    This is just for a learning example.  Also, some web hosts don't allow URL fetching with file_get_contents.

You can download the file here: File:jquery-helper.zip

I welcome your comments.

Thanks, -Brodie

Clone this wiki locally