One of the challenges in developing ajax application using CakePHP is to figure out how to load ajax view (interface) for first time and request only data (json or XML) in subsequent ajax calls. Luckily, with CakePHP this is simple and you really don’t need to write many different functions. The trick is to use ParseExtension and RequestHandler. You can read more about ParseExtension and requestHandler in CakePHP cookbook (here are links ParseExtension and requestHandler)
Even after reading about ParseExtension and requestHandler, if you have question on how to develop ajax application using CakePHP, then continue reading .
Lets assume that you want to display all the registered users of an application. If you have thousands of users, you don’t want to show all of them at once but use pagination. Now, lets assume that you have Ajax Table with a pagination toolbar( somthing like this example). Further, users can access this page by reaching to the following URL – http://localhost/users/index. This page renders the table, paging toolbar and loads first 10 registered users.
1. views/users/index.ctp – this view creates table structure, paging toolbar and, if available, loads initial data
2. views/users/json/index.ctp - this view only sends json data to the browser
Below is a diagram that indicates how query/request/data flow across different components when developing a ajax application using the above approach. Note, the diagram shows my approach and is not endorsed by CakePHP or any other group. Thus, there might be other approaches that might be more efficient than mine. The numbers in the image indicate how query/data flow from one component to another and is explaind below the image.
1. A User requests for http://localhost/users/index page
2. ”User controller” then calls “user model” to get first 10 registered users
3. Model returns data
4. ”User Controller” sends data to the view that is located at “views/users/index.ctp” In this view, we remotely set ajax functions to call http://localhost/users/index.json (note extra “.json” at the end of the URL).
5. Rendered table, pagination toolbar and initial data is to the brower is passed to the browser and is rendered by the browser engine.
6. Users clicks on “next” button on the pagination toolbar
7. Next button sends an ajax calls to http://localhost/users/index.json and also query parameter such as page 2, limit 10, etc.
8. Controller sends parameters to the model
9. Model sends data back to controller
11. The json data from the second view is passed to the browser (or table ), completing the ajax request.
Let me know if you have used any other approach to develop ajax applications.
Posted in CakePHP, General Tagged: Ajax, CakePHP