Ajax.cfc is just another model in your MG application, used by the controller to manipulate data. You can initialize it in your Controller’s init function and store in persistently in the controller’s variables scope.
The Ajax remote request call flows exactly (or almost) like a traditional call. It flows as follow:
- Page triggers an AJAX request.
- The event will be caught by the MG framework.
- The MG event-handler will broadcast a message.
- The controller will pickup the message.
- The controller will AJAX model to parse it (onRequestStart)
- The controller can use other models at will (theEvent)
- The controller uses the AJAX model to prepare the reponse.
- The controller sets the ‘ajaxResponse’ value back to be used by the view
Alright, so this may sound complicated, but it really isn’t. The flow is exactly like any other page with the exception of:
- You need to parse the Ajax request with the Ajax model.
- You will received a structure with two elements
i. id: the unique identifier of the Ajax remote call request
- My example parses the values in the controller’s onRequestStart and place them in the request scope to be picked up later by the requested method.
- Optionally, you may invoke security and debugging functions contained in the Ajax model.
- You need to prepare the response before sending it back to the framework. You will use the Ajax.returnAjax method to do so. The returnAjax method always takes your response and the Ajax call unique identifier.
- You need to set the ajaxResponse value to be used by the view.
- Finally, include the ajaxResponse.cfm file that simply displays the ajaxResponse value sent by the controller.
While I do not recommend leaving business logic at the client side, because it defeats the entire MVC and thus MG framework, it is the easiest way to get started with Ajax.
In my next example, I will show how to leave all the business logic in the server side, contained in views, and leave only connectivity functions in the client side.
If you have any comments / requests, do not hesitate to comment or contact me and I will do my best to add them to the framework.