views:

63

answers:

2

i have a User Module where users can set their status message (tweet) from the profile page.

alt text

When some one clicks Share it should go to an action and save the status message. I am not sure how to do this in CakePHP.

I would wnna use jQuery. If you can point me to the right document. it would be of great help

I am new to Ajax.

+1  A: 

Forms are submitted via ajax in exactly the same way they might be without CakePHP. If it's me, Here's what I'd do...

In my view:

<?php echo $this->Html->script( 
  array( 'vendors/jquery.min', 'customjs' )
  , array( 'inline' => false, 'once' => true ) 
) ?>

<?php echo $this->Form->create( ... ) ?>
  ... your form content here ...
<?php echo $this->Form->end( 'Share' ) ?>

In a custom Javascript file (/js/custom.js):

$(function() {
  $('#your-form' ).submit( function() {
    // make your ajax call
    $.post( ... );

    return false; // prevent a new request
  });
});

Finally, create a new controller and/or action to handle the URL being requested by your ajax call. Those are just the highlights, of course, but they illustrate the key distribution of concerns:

  1. Include the necessary JS files so your view has access to them.
  2. Attach the submit event handler on document.ready (not inline)
  3. Prevent the form from performing its regularly scheduled submit after the ajax call by returning false from the event handler.

Hope that helps.

Rob Wilkerson
Thanks Rob. will try it and get back to u :D
Harsha M V
+1  A: 

CakePHP has a Js Helper which uses the JQuery library by default. The method you are looking for is the submit() method.

An example usage would be:

    <?php echo $form->create('Tweet'); ?>
    <!-- form elements -->
    <?php echo $this->Js->submit('Share',
                                array(
                                    'update' => '#content'
                                )
                            ); ?>

The contents of the element #content would be changed with the HTML returned from the controller.

In the action where the ajax form will be submitted, add() in the example above, you might want to change the layout to ajax whenever an ajax request is detected. You could do this using the isAjax() method and the controller's $layout attribute.

Ramon Marco Navarro
I hate to hijack a discussion, but I am having issues with the Js helper. (Ramon, you attempted to answer my question last week http://stackoverflow.com/questions/3901906/how-to-use-js-submit-in-cakephp ). What does the "Share" refer to in the submit() options array? Did this work for you Harsha?
Logic Artist
@Logic Artist: Thanks for pointing that out. I've corrected the snippet.
Ramon Marco Navarro