Tuesday, April 6, 2010

Using JSON in CakePHP 1.2

Recently, I was doing a project that required me to make two drop-down menus related to each other. The scenario was if you chose a company from a list of drop-down list of companies, the subsequent contacts drop-down would only be populated with contacts specific to the company chosen. I knew from past experience that I would be able to do this if I could get the contacts served to me as JSON. Then I stumbled upon this article that explains in a very simple way how to get CakePHP 1.2 (NOTE: This works with 1.3 as well) to return JSON via a view.

http://www.pagebakers.nl/2007/06/05/using-json-in-cakephp-12/

One point of note, it was a little confusing where to put the .json extension on the URL to make this work correctly. Just so there is no confusion, this is always at the end of the URL. For my use in getting the contacts I needed the URL was "/contacts/view/1.json" where 1 is the company ID.

Another link treasure I discovered during this process was this link from Remy Sharp's blog:

http://remysharp.com/2007/01/20/auto-populating-select-boxes-using-jquery-ajax/