dinsdag 19 februari 2008

Ajax is so easy...

Ok, download CakePHP 1.2 and create a basic website with some scaffolding or something. Include Prototype or jQuery and think about a part of your page you want to replace with the result of an Ajax request.

Suppose you have a scaffolded list of customers. When you press the View link, Cake redirects you to customers/view/123. You can catch the link and call some Javascript to load the result of customers/view/123 in a div on your index page. Quite easy, but you now see your header twice. Not cool. Hmmm....

Try to load the component RequestHandler.

Hey Cool! My layout is gone and my Ajax function does what I want.

Actually, your layout is not gone, but Cake detects that the view was loaded from an Xmlhttprequest (ajax) and uses the Ajax layout instead of the default.

Try this at home!

5 opmerkingen:

  1. Is this automatic or do you need to add code?

    BeantwoordenVerwijderen
  2. Yes, wow. It is automatic. I've found it necessary to do the following however:
    1. Element for the controller. Essentially a stripped view of the controller. Since I'm using jQuery, I put my
    $(document).ready(function() code in there also, with all my hides, shows and slides.

    2. The view for my controller consists of the div I need to populate (and my loading div) and within this div, the element from above.

    3. At the end of the controller, the following:
    if($this->RequestHandler->isAjax()) {
    $this->viewPath = 'elements';
    $this->render('controllerElement');
    }

    It's a bit simpler if you use the Ajax helper.

    BeantwoordenVerwijderen
  3. Hey Baz L,

    I was just thinking yesterday about a place to put my jQuery code. Sounds like a good idea of yours to put this in an element. But, do you make one big element, or do you have an element per view, or do you have one element with if statements to load only the jQuery code you need for your current view?

    BeantwoordenVerwijderen
  4. There´s a jQuery helper to you make the include in the header and then the developer dont need to use the script like a element.

    BeantwoordenVerwijderen
  5. sorry i'm newbie in cakephp and ajax..
    could u please upload ur sample code here..or u can email to me...
    thanks...

    BeantwoordenVerwijderen