CakePHP and Jquery

When you develop web applications or user friendly websites (you should always do this when creating a site) you’ll encounter the need to add javascript to you project.
Now, we all know and it is recommended that you shouldn’t write pure javascript code anymore (unless you really need to) but use a framework.
Jquery is a very [...]

When you develop web applications or user friendly websites (you should always do this when creating a site) you’ll encounter the need to add javascript to you project.

Now, we all know and it is recommended that you shouldn’t write pure javascript code anymore (unless you really need to) but use a framework.

Jquery is a very good example of a such framework. You can develop ultra fast scripts that would have taken days/weeks/months in pure javascript.

Now, lets get to business : our issue is to dynamically add stuff to our cakephp view with jquery. And we also want that this stuff to contain dynamic data from our controller (for example we want to add a container with a select box which has dynamic data into it, and furthermore, a dynamic selection from that select box)After doing a lot of researching on the web, the conclusion was that, the best way to do this would be to send from the controller some J SON vars to the view and then render them as a java script block that Jquery would interpret and do stuff with or use elements that you render in your view, in a javascript variable.

We will not discuss about the JSON option but instead we will talk about jquery and cakephp elements.

Basically, in our example, we will use a special view, an element, to have all the data we want, and then just fetch it from the view into a javascript variable that we can render on the page. It is allmost the same thing as with the JSON vars but its alot more cleaner.

Cake Controller :

$fields = $this->Field->find('list',$my_sql_parameters);
$this->set("fields","1");
$this->set("my_selected_field_id","1");

Cake View


Cake Element

 $val) {
$sel = "";
if ($key == $selected) $sel = 'selected="selected"';
echo ''.$val.'';
}
?>

Its very simple yet intuitive to change/modify in the future and you dont need the JSON cake helper.

Hope it helped!

  • Agoodprogrammer
    Good information here, but I have to say the site title is a bit cheesy.
  • indeed. new design INC soon though ;)
  • Beda1708
    sir,
    i am a newbie and am in need of a tool like the one you have described before.
    but i could not understand it fully. can you please post a more elaborate example.
    (a simple one - with two or three drop downs in the select list, but complete view file and element file). thanksin advance
blog comments powered by Disqus


Popular tags

Partner Blogs

Latest tweets


Get Adobe Flash playerPlugin by wpburn.com wordpress themes
Web Analytics