Skip to content

Ajax Framework For CodeIgniter

ajaxboy edited this page Aug 18, 2016 · 136 revisions

Category:Ajax Frameworks Category:Library::AJAX Category:Ajax applications Category:Applications

***IMPORTANT UPDATE***
For Codeigniter 3.x,  you need to use CJAX 5.9 (You can download straight 
from Github (https://github.com/ajaxboy/cjax)


Cjax 5.8 is not compatible with CI 3.x,  but there are instructions 
available how you can make it compatible. 
See instructions: http://forum.codeigniter.com/thread-65918-post-335584.html 

(For more examples and docs visit http://cjax.sourceforge.net)

A very basic but powerful implementation of Ajax Framework that complements Codeigniter.

New Download Location: Download here

Get the latest Version

https://github.com/ajaxboy/cjax

Cjax Framework separates your ajax controllers from your regular controllers. While your normal controllers reside in application/controllers, your ajax controllers will reside in application/response.

Install

Download and unzip the Ajax Framework package, then just overwrite everything from the zip into your CodeIgniter base installation (will not replace any of your files)

Test

just go to:

http://yoursite.com/ajax.php?test/test

(replace http://yoursite.com with the base directory where your CodeIgniter installation resides)

To this point you are done, successfully installing and using Cjax, if the test above prints shows a success message. You can find this text inside file application/views/test.php, and its controller in application/response/test.php.

Demos

http://cjax.sourceforge.net/examples/

https://github.com/ajaxboy/cjax

The demos, have samples codes that you can use. There is also documentation available on the demos page. http://cjax.sourceforge.net/examples/. The demos come already included when you download and install Cjax.

Friendly URLS

Full support for friendly URLS.

Friendly URLS are supported, but not required to use Cjax. You may access your controllers in any of the following ways; these examples make use of controller file application/response/test.php.

//ajax.php?controller=$controller&function;=$function
ajax.php?controller=test&function=test
//ajax.php?$controller/$function
ajax.php?test/test
//ajax/$controller/$function

#as of 5.0beta2
ajax.php/$controller/$function

#This one requires mod_rewrite
ajax/test/test

The last url above, will require you to enable mod_rewrite in your server and rename the accompanied file htaccess.txt File:htaccess.txt to .htacccess

Creating Controllers

Creating controllers works the same way as your regular controllers. You may also start your class name with an underscore "_" if for any reason you happen to experience class name conflict.

Example

application/response/test.php ```php class test extends CI_Controller {
function test()
{

}

}

You may use your ajax controller the same way you would use any other CI controller including the creation of any dependencies.


<h2>Passing Parameters</h2>

Cjax uses URL query string to pass parameters into the controller by using function parameters. You can pass alphabetic letters as parameter order to your methods inside the controllers. There is more than one way to pass parameters, depending on the way you are using the URL.

Example of passing parameters in followed order.

URL: 
```php

ajax.php?test/test/arg1/someID
// this also applies to mod_rewrite urls such as: ajax/test/test/arg1/someID

The above URL is passing two parameters arg2 and someID, test/test indicates the controller and the method. To access these parameters use function arguments:

Example

application/response/test.php ```php class Test extends CI_Controller {
function test($arg1, $arg2)
{
    echo $arg1;
    echo "<br />";
    echo $arg2;
}
//prints  arg1
//        someID

}


You can pass unlimited number of parameters, and access them through function parameters in the same order they are passed.  



<h4>Alphabetic order Parameters</h4>
A less Organized way to pass parameters that may accept any order within the URL: 

URL:
```php
ajax.php?controller=test&function=test&a=Hello&b=World&c=Hello World

The previous URL, makes use of common URL, and passes three parameters to the controller.

This methods accepts any alphabetic letter in respective order to pass parameters. You may pass: a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z, which will be accessible through function parameter. Using this method also allows you to pass any other parameters through outside of the function parameter scope.

Example

application/response/test.php ```php class controller_test extends CI_Controller {
function test($a, $b, $c)
{
    echo $a;
    echo "<br />";
    echo $b;
    echo "<br />";
    echo $c;
}
//prints  Hello
//        World
//        Hello World

}



<h2>Advanced Usage</h2>


Bellow are some more advanced ways to use this ajax framework. The level of expertize required is advanced intermediate, if you feel confident, do read through it. Not all the APIs will be covered here, however some of the most used ones will.


<h2>Using Ajax Framework JavaScript Library</h2>
So far you have experienced the basic power of this framework through a php environment, but this framework also offers a taste of JavaScript.


To initialize the JavaScript library included with Cjax,  have the <b>$ajax</b> Object do it for you, simply in the <b>HEAD</b> of the HTML page do:

```html
<!doctype html>
<head>
    <title>Test</title>
    <?php echo $ajax->init();?>
</head>
<body>

$ajax->init() will print the script tag of cjax.js. As of version 5.0-beta, By default the minified version of cjax.js is invoked, but you can change that by passing false in the init function, eg: $ajax->init(false), then the full version would be used.

  • OR - a work around for using init() function -

Simply include file in the head of your HTML document:

cjax/core/js/cjax.min.js

(for full none minified version remove the '.min' suffix).

Event Request

The purpose of this section is to illustrate how to use utilities included within the framework, and how they are executed, not necessarily how to use ajax.

The js Lib, offers two event request types, which are executed when page first loads and each time you make an ajax request.

You may use this Framework to create ajax requests or you may use any other method, but we recommend either using this framework or using Jquery. See at the bottom of this page how to integrate this framework with any other ajax request application or method.

Framework Usage of JavaScript

This framework does not make use of JavaScript directly. It does however uses the js lib indirectly, by creating XML or Json commands that are later passes to the interpreter which executes commands which fires functions included in the js library (cjax.min.js).

This allows you to create all your ajax framework code in a php environment, rather than a JavaScript one. But also gives you a lot of tools and the environment for you create your custom JavaScript, and execute with Cjax.

Create ajax request

Within your main controller, include file ajaxfw.php

in your main controller:

$this->load->file(FCPATH.'application/libraries/ajax.php');

Then you can make full use of the ajax framework in a local scope within your controller.

You may instantiate ajax by using the following method:

$ajax = ajax();

Important: As of Cjax version 4.1RC1 you may instantiate Cjax as Follows:

$ajax = ajax();

If you are using a previous version, you will need to do it this way:

$ajax = ajax();

Hello Application

Now lets make some anchors fire an ajax request, and handle the hello request with the server.

$ajax->Exec&#40;'achor1',$ajax->call('ajax.php?test/test/Hello'&#41;);

The above line will create an event listener ajax request attached to click event to a DOM element with id 'anchor1'.

Same result using Jquery:

$(document).ready(function(){
 $('#achor1').click(function(){
  $.get('ajax.php?test/test/Hello', function(response) {
 
  })
 });
}); 

In your view file.. lets add that anchor:

Note

You may add event listeners the same way to about any DOM element such as buttons, images, and of course anchors etc.

views/test.php

&lt;body&gt;
<a id='anchor1' href='#'>Anchor 1</a>
&lt;/body&gt;

When you click on the link, it will fire the ajax request directed to: ajax.php?test/test/Hello.

Server Side

Now that the ajax request has fired, it will trigger method test() inside class controller_test in application/response/test.php.

We'll show a message in the screen, see below a list of messaging types.

Messaging API:

  • success
  • error
  • info
  • warning

At this point we are within the ajax server side scope, so we do not need to include any files, we just need to instantiate the ajax class.

class controller_test extends CI_Controller {

    function test($hello)
    {
        $ajax = ajax();
        $ajax->success($hello);
    }
}

The word Hello is passed through the ajax call parameter, and we make use of the ajax messaging api to display a success message in the middle screen.

Each message function is pre-configured to stay on the screen for three seconds, but you may change that with a second parameter, lets try 10 seconds:

$ajax->success($hello, 10);

You may use any of these messaging API functions:

Try them.. one at a time.

$ajax->success($hello);

$ajax->error($hello);

$ajax->info($hello);

$ajax->warning($hello);

You cannot use more than one message API at the same time because the next message will remove the previous, and you will not be able to see them, except the last one.

Cjax has a handy function that allows you to by pass this behavior, the wait() function. You may call wait() each time one of them is fired as follow:

$ajax->success($hello);

$ajax->wait(3);

$ajax->error($hello);

$ajax->wait(3);

$ajax->info($hello);

$ajax->wait(3);

$ajax->warning($hello);

You will be able to see each one of the message for three seconds. There is no real world use for this, but it is a demonstration of the usage of timeouts. You may use timeouts for most API functions within the framework.

Submit Ajax Form

To Submit Ajax form is quite simple and straight forward.

First have your HTML form ready.

In your view or controller, then you do this:

//(5.0-RC1+)
$ajax->button_id = $ajax->form('ajax.php?form/submit'); 

"button_id", is the DOM HTML id of your submit button inside your HTML form. You may use an image or a link or a submit button to submit.

As per the example above, indicates you would need to create a controller file application/response/form.php, and a class 'form', then a function submit.

You may access the values of the form in your Ajax controller through $_REQUEST, or $_POST or CI input sanitation function, you may also access your form values in the controllers parameters if you use a,b,c,d,e,f etc in your form fields ids.

Before 5.0-RC1, this is how you would accomplish this:

$ajax->Exec&#40;'button_id', $ajax->form('ajax.php?form/submit','form_id'&#41;); 

Recursive Ajax Requests

Using the same Hello Application, we'll create recursive ajax requests, each 5 seconds.

class controller_test extends CI_Controller {

    function test($hello)
    {
        $ajax = ajax();

        $ajax->wait(5);

        $ajax->call("ajax.php?test/test/hello");
    }
}

The above example will trigger ajax requests to the same method, recursively every 5 seconds.

Update Containers

You can update any div, span containers or text/HTML elements on the page using the update(); function.

Example

application/response/test.php ```php class controller_test extends CI_Controller {
function test()
{
    $ajax  = ajax();

    $ajax->update("Div_id","html here");
}

}


In CJAX 5.0+ You can update elements this way:

application/response/test.php
```php
class controller_test extends CI_Controller {

    function test()
    {
        $ajax  = ajax();

        $ajax->Div_id = "html here";
    }

}

You may also update any other inputs or elements using the method above.

Overlays Lightbox

Watch Video Demonstration [quote] http://www.youtube.com/watch?v=KCJkcLEK-X4 [/quote]

One of the fancy features of Cjax is how easy is to create overlays without much code foot print. Lets take our Hello Application and use it instead of the messaging.

Basic use of OverlayCotent()

```php class controller_test extends CI_Controller {
function test($hello)
{
    $ajax = ajax();
    $ajax->overlayContent($hello);
}

}


Above is the raw basic use of an overlay, you may pass any html or template in the first parameter, and it will show it in  the overlay.

Now lets show some configuration  and customization:

You may control, how transparent the overlay is, color, and position within the screen, top and left positioning.

<h3>Overlay using Options</h3>
```php
class controller_test extends CI_Controller {

    function test($hello)
    {
        $ajax = ajax();
        
        $options['transparent'] = 10;
        $options['color'] = '#425769';
        $options['top']  =  200;
        $options['left'] = "50%";
        
        $ajax->overlayContent($hello, $options);
    }
}

You may also format the dialog message within the overlay as follows (you maybe still pass the options if desired.):

Overlay using formatting

```php class controller_test extends CI_Controller {
function test($hello)
{
    $ajax = ajax();
    
    $html = $ajax->dialog($hello,"Hello Application");
    
    $ajax->overlayContent($html);
}

}


<h3>Fetching a URL</h3>

The overLay() function fetches a URL and places the response html inside the overlay.

The next example will fire an ajax request and get the html, and set it within the overlay.

<h3>Overlay URL</h3>
```php
class controller_test extends CI_Controller {

    function test($hello)
    {
        $ajax = ajax();
        
        
        $ajax->overlay("ajax.php?test/html");
    }

    function html()
    {
        
        echo "some html fetched through ajax";
    }
}

Configuring the framework with other ajax requests

You can hook any XHR request with this Framework, If you use your custom code to create ajax request or use some other framework or library, you may also be able to allow it to execute all these commands, here is how:

Each time an ajax request is created, it returns a response text, the framework processes this text to find possible commands to execute, all commands are parsed from an XML format.

This is the generic code needed to allow any ajax request to process the commands:

after you have created the request, use the response text as such:

if(typeof CJAX != 'undefined') {
    CJAX.process_all(response); // your response text goes here
}

Jquery

The Ajax Framework is already configured to automatically detect any Jquery request through the complete() function callback in Jquery Ajax. So you do not need to do any extra steps if your request originated from the framework or from Jquery.

Creating AJAX Framework (4.2+) Plugins

Put bluntly, with the Ajax Framework you can literally execute JavaScript from PHP, and with Cjax Plugins you can execute your own custom JavaScript Code through $ajax object from PHP anywhere in your application. This makes it handy dandy, for you to consolidate solid functionality through your application, and easily execute without having to get your hands dirty with chunks of JavaScript everywhere. You maybe be able to create widgets if you let your imagination fly.

There is available documentation for plugins, you may download plugin samples here:

Download Advanced Plugin Example (5.0+)

http://code.google.com/p/ajax-framework-for-codeigniter/downloads/detail?name=4Developers.ExamplePlugin.API.zip

Download Basic Plugin Example (5.0+)

http://code.google.com/p/ajax-framework-for-codeigniter/downloads/detail?name=4Developers.basic-plugin.zip

Scope

Plugins can be executed on page load, or within every ajax request.

Steps for creating a plugin

1. Create a Javascript file under cjax/plugins/YourPlugin.js
    
    Or you may also create a directory inside plugins directory like so:  
    cjax/plugins/YourPlugin/YourPlugin.js,  In case you want to add additional css,         images, or other media, etc.

2. Add a function YourPlugin in YourPlugin.js
         function YourPlugin() {}

Call your plugin

    $ajax->YourPlugin()
3. Replace "YourPlugin" with the name of your plugin
4. Pass parameters
    You may pass strings or arrays through function parameters through your php plugin call.
        $ajax->YourPlugin('pass strings', array('pass'=>'arrays'))

** Acess parameters in your JavaScript Plugin**

                    //cjax/plugins/YourPlugin.js
                    function YourPlugin(str, arr) {
                         
                         //YOUR CUSTOM CODE HERE
                         alert(str&#41;;
                         //alerts all the items in your array.
                         for(item in arr&#41; {
                              alert(item+ ' '+arr[item]&#41;;
                          }
                     }
      Arrays are converted to Json objects, that is how you would access them.

Creating a plugin, couldn't be easier...

Plugin API

Plugins have fast access to some of the core functionality provided in the framework, plugins are able to quickly create ajax request, overlays, messages, dialogs - with JavaScript.

With the newly released version 5.0, now you can also use PHP to create plugins, to give even more power to your plugins.

Clone this wiki locally