Welcome to the Cookbook

loading...

7.1.2 Methods

There is no translation yet for this section. Please help out and translate this.. More information about translations

link(string $title, mixed $href, array $options, string $confirm, boolean $escapeTitle)

Returns a link to a remote action defined by $options['url'] or $href that's called in the background using XMLHttpRequest when the link is clicked. The result of that request can then be inserted into a DOM object whose id can be specified with $options['update'].

If $options['url'] is blank the href is used instead

Example:

<div id="post">
</div>
<?php echo $ajax->link( 
    'View Post', 
    array( 'controller' => 'posts', 'action' => 'view', 1 ), 
    array( 'update' => 'post' )
); 
?>
  1. <div id="post">
  2. </div>
  3. <?php echo $ajax->link(
  4. 'View Post',
  5. array( 'controller' => 'posts', 'action' => 'view', 1 ),
  6. array( 'update' => 'post' )
  7. );
  8. ?>

By default, these remote requests are processed asynchronously during which various callbacks can be triggered

Example:

<div id="post">
</div>
<?php echo $ajax->link( 
    'View Post', 
    array( 'controller' => 'posts', 'action' => 'post', 1 ), 
    array( 'update' => 'post', 'complete' => 'alert( "Hello World" )'  )
); 
?>
  1. <div id="post">
  2. </div>
  3. <?php echo $ajax->link(
  4. 'View Post',
  5. array( 'controller' => 'posts', 'action' => 'post', 1 ),
  6. array( 'update' => 'post', 'complete' => 'alert( "Hello World" )' )
  7. );
  8. ?>

To use synchronous processing specify $options['type'] = 'synchronous'.

To automatically set the ajax layout include the RequestHandler component in your controller

By default the contents of the target element are replaced. To change this behaviour set the $options['position']

Example:

<div id="post">
</div>
<?php echo $ajax->link( 
    'View Post', 
    array( 'controller' => 'posts', 'action' => 'view', 1), 
    array( 'update' => 'post', 'position' => 'top'  )
); 
?>
  1. <div id="post">
  2. </div>
  3. <?php echo $ajax->link(
  4. 'View Post',
  5. array( 'controller' => 'posts', 'action' => 'view', 1),
  6. array( 'update' => 'post', 'position' => 'top' )
  7. );
  8. ?>

$confirm can be used to call up a JavaScript confirm() message before the request is run. Allowing the user to prevent execution.

Example:

<div id="post">
</div>
<?php echo $ajax->link( 
    'Delete Post', 
    array( 'controller' => 'posts', 'action' => 'delete', 1 ), 
    array( 'update' => 'post' ),
    'Do you want to delete this post?'
); 
?>
  1. <div id="post">
  2. </div>
  3. <?php echo $ajax->link(
  4. 'Delete Post',
  5. array( 'controller' => 'posts', 'action' => 'delete', 1 ),
  6. array( 'update' => 'post' ),
  7. 'Do you want to delete this post?'
  8. );
  9. ?>

7.1.2.2 remoteFunction

There is no translation yet for this section. Please help out and translate this.. More information about translations

remoteFunction(array $options);

This function creates the JavaScript needed to make a remote call. It is primarily used as a helper for link(). This is not used very often unless you need to generate some custom scripting.

The $options for this function are the same as for the link method

Example:

<div id="post">
</div>
<script type="text/javascript">
<?php echo $ajax->remoteFunction( 
    array( 
        'url' => array( 'controller' => 'posts', 'action' => 'view', 1 ), 
        'update' => 'post' 
    ) 
); ?>
</script>
  1. <div id="post">
  2. </div>
  3. <script type="text/javascript">
  4. <?php echo $ajax->remoteFunction(
  5. array(
  6. 'url' => array( 'controller' => 'posts', 'action' => 'view', 1 ),
  7. 'update' => 'post'
  8. )
  9. ); ?>
  10. </script>

It can also be assigned to HTML Event Attributes:

<?php 
    $remoteFunction = $ajax->remoteFunction( 
        array( 
        'url' => array( 'controller' => 'posts', 'action' => 'view', 1 ),
        'update' => 'post' ) 
    ); 
?>
<div id="post" onmouseover="<?php echo $remoteFunction; ?>" >
Mouse Over This
</div>
  1. <?php
  2. $remoteFunction = $ajax->remoteFunction(
  3. array(
  4. 'url' => array( 'controller' => 'posts', 'action' => 'view', 1 ),
  5. 'update' => 'post' )
  6. );
  7. ?>
  8. <div id="post" onmouseover="<?php echo $remoteFunction; ?>" >
  9. Mouse Over This
  10. </div>

If $options['update'] is not passed, the browser will ignore the server response.

7.1.2.3 remoteTimer

There is no translation yet for this section. Please help out and translate this.. More information about translations

remoteTimer(array $options)

Periodically calls the action at $options['url'], every $options['frequency'] seconds. Usually used to update a specific div (specified by $options['update']) with the result of the remote call. Callbacks can be used.

remoteTimer is the same as the remoteFunction except for the extra $options['frequency']

Example:

<div id="post">
</div>
<?php
echo $ajax->remoteTimer(
	array(
	'url' => array( 'controller' => 'posts', 'action' => 'view', 1 ),
	'update' => 'post', 'complete' => 'alert( "request completed" )',
	'position' => 'bottom', 'frequency' => 5
	)
);
?>
  1. <div id="post">
  2. </div>
  3. <?php
  4. echo $ajax->remoteTimer(
  5. array(
  6. 'url' => array( 'controller' => 'posts', 'action' => 'view', 1 ),
  7. 'update' => 'post', 'complete' => 'alert( "request completed" )',
  8. 'position' => 'bottom', 'frequency' => 5
  9. )
  10. );
  11. ?>

The default $options['frequency'] is 10 seconds

7.1.2.4 form

There is no translation yet for this section. Please help out and translate this.. More information about translations

form(string $action, string $type, array $options)

Returns a form tag that submits to $action using XMLHttpRequest instead of a normal HTTP request via $type ('post' or 'get'). Otherwise, form submission will behave exactly like normal: data submitted is available at $this->data inside your controllers. If $options['update'] is specified, it will be updated with the resulting document. Callbacks can be used.

The options array should include the model name e.g.
$ajax->form('edit','post',array('model'=>'User','update'=>'UserInfoDiv'));
  1. $ajax->form('edit','post',array('model'=>'User','update'=>'UserInfoDiv'));
Alternatively, if you need to cross post to another controller from your form:
$ajax->form(array('type' => 'post',
    'options' => array(
        'model'=>'User',
        'update'=>'UserInfoDiv',
        'url' => array(
            'controller' => 'comments',
            'action' => 'edit'
        )
    )
));
  1. $ajax->form(array('type' => 'post',
  2. 'options' => array(
  3. 'model'=>'User',
  4. 'update'=>'UserInfoDiv',
  5. 'url' => array(
  6. 'controller' => 'comments',
  7. 'action' => 'edit'
  8. )
  9. )
  10. ));

You should not use the $ajax->form() and $ajax->submit() in the same form. If you want the form validation to work properly use the $ajax->submit() method as shown below.

7.1.2.5 submit

There is no translation yet for this section. Please help out and translate this.. More information about translations

submit(string $title, array $options)

Returns a submit button that submits the form to $options['url'] and updates the div specified in $options['update']

<div id='testdiv'>
<?php
echo $form->create('User');
echo $form->input('email');
echo $form->input('name');
echo $ajax->submit('Submit', array('url'=> array('controller'=>'users', 'action'=>'add'), 'update' => 'testdiv'));
echo $form->end();
?>
</div>
  1. <div id='testdiv'>
  2. <?php
  3. echo $form->create('User');
  4. echo $form->input('email');
  5. echo $form->input('name');
  6. echo $ajax->submit('Submit', array('url'=> array('controller'=>'users', 'action'=>'add'), 'update' => 'testdiv'));
  7. echo $form->end();
  8. ?>
  9. </div>

Use the $ajax->submit() method if you want form validation to work properly. i.e. You want the messages you specify in your validation rules to show up correctly.

7.1.2.6 observeField

There is no translation yet for this section. Please help out and translate this.. More information about translations

observeField(string $field, array $options)

Observes the field with the DOM id specified by $field (every $options['frequency'] seconds) and makes an XMLHttpRequest when its contents have changed.

When no frequency or a small frequency interval (between 0 and 1) is specified, a prototype Form.Element.EventObserver will be used instead of a Form.Element.Observer. The Form.Element.EventObserver is not timed and will execute at the same time the value of the element has changed.

<?php echo $form->create( 'Post' ); ?>
<?php $titles = array( 1 => 'Tom', 2 => 'Dick', 3 => 'Harry' ); ?>	
<?php echo $form->input( 'title', array( 'options' => $titles ) ) ?>
</form>

<?php 
echo $ajax->observeField( 'PostTitle', 
    array(
        'url' => array( 'action' => 'edit' ),
        'frequency' => 0.2,
    ) 
); 
?>
  1. <?php echo $form->create( 'Post' ); ?>
  2. <?php $titles = array( 1 => 'Tom', 2 => 'Dick', 3 => 'Harry' ); ?>
  3. <?php echo $form->input( 'title', array( 'options' => $titles ) ) ?>
  4. </form>
  5. <?php
  6. echo $ajax->observeField( 'PostTitle',
  7. array(
  8. 'url' => array( 'action' => 'edit' ),
  9. 'frequency' => 0.2,
  10. )
  11. );
  12. ?>

observeField uses the same options as link

The field to send up can be set using $options['with']. This defaults to Form.Element.serialize('$field'). Data submitted is available at $this->data inside your controllers. Callbacks can be used with this function.

To send up the entire form when the field changes use $options['with'] = Form.serialize( $('Form ID') )

7.1.2.7 observeForm

There is no translation yet for this section. Please help out and translate this.. More information about translations

observeForm(string $form, array $options)

Similar to observeField(), but operates on an entire form identified by the DOM id $form. The supplied $options are the same as observeField(), except the default value of the $options['with'] option evaluates to the serialized (request string) value of the form.

7.1.2.8 autoComplete

There is no translation yet for this section. Please help out and translate this.. More information about translations

autoComplete(string $field, string $url, array $options)

Renders a text field with $field with autocomplete. The remote action at $url should return a suitable list of autocomplete terms. Often an unordered list is used for this. First, you need to set up a controller action that fetches and organizes the data you'll need for your list, based on user input:

function autoComplete() {
	//Partial strings will come from the autocomplete field as
	//$this->data['Post']['subject'] 
	$this->set('posts', $this->Post->find('all', array(
				'conditions' => array(
					'Post.subject LIKE' => $this->data['Post']['subject'].'%'
				),
				'fields' => array('subject')
	)));
	$this->layout = 'ajax';
}
  1. function autoComplete() {
  2. //Partial strings will come from the autocomplete field as
  3. //$this->data['Post']['subject']
  4. $this->set('posts', $this->Post->find('all', array(
  5. 'conditions' => array(
  6. 'Post.subject LIKE' => $this->data['Post']['subject'].'%'
  7. ),
  8. 'fields' => array('subject')
  9. )));
  10. $this->layout = 'ajax';
  11. }

Next, create app/views/posts/auto_complete.ctp that uses that data and creates an unordered list in (X)HTML:

<ul>
 <?php foreach($posts as $post): ?>
     <li><?php echo $post['Post']['subject']; ?></li>
 <?php endforeach; ?>
</ul> 
  1. <ul>
  2. <?php foreach($posts as $post): ?>
  3. <li><?php echo $post['Post']['subject']; ?></li>
  4. <?php endforeach; ?>
  5. </ul>

Finally, utilize autoComplete() in a view to create your auto-completing form field:

<?php echo $form->create('User', array('url' => '/users/index')); ?>
	<?php echo $ajax->autoComplete('Post.subject', '/posts/autoComplete')?>
<?php echo $form->end('View Post')?>
  1. <?php echo $form->create('User', array('url' => '/users/index')); ?>
  2. <?php echo $ajax->autoComplete('Post.subject', '/posts/autoComplete')?>
  3. <?php echo $form->end('View Post')?>

Once you've got the autoComplete() call working correctly, use CSS to style the auto-complete suggestion box. You might end up using something similar to the following:

div.auto_complete    {
     position         :absolute;
     width            :250px;
     background-color :white;
     border           :1px solid #888;
     margin           :0px;
     padding          :0px;
} 
li.selected    { background-color: #ffb; }

If you want the user to enter a minimum number of characters before the autocomplete starts, you can use the minChars-Option as follows:

$ajax->autoComplete('Post.subject', '/posts/autoComplete',array('minChars' => 3));
  1. $ajax->autoComplete('Post.subject', '/posts/autoComplete',array('minChars' => 3));

7.1.2.9 isAjax

There is no translation yet for this section. Please help out and translate this.. More information about translations

isAjax()

Allows you to check if the current request is a Prototype Ajax request inside a view. Returns a boolean. Can be used for presentational logic to show/hide blocks of content.

7.1.2.10 drag & drop

There is no translation yet for this section. Please help out and translate this.. More information about translations

drag(string $id, array $options)

Makes a Draggable element out of the DOM element specified by $id. For more information on the parameters accepted in $options see http://github.com/madrobby/scriptaculous/wikis/draggable.

Common options might include:

$options keys Description
$options['handle'] Sets whether the element should only be draggable by an embedded handle. The value must be an element reference or element id or a string referencing a CSS class value. The first child/grandchild/etc. element found within the element that has this CSS class value will be used as the handle.
$options['revert'] If set to true, the element returns to its original position when the drags ends. Revert can also be an arbitrary function reference, called when the drag ends.
$options['constraint'] Constrains the drag to either 'horizontal' or 'vertical', leave blank for no constraints.

drop(string $id, array $options)

Makes the DOM element specified by $id able to accept dropped elements. Additional parameters can be specified with $options. For more information see http://github.com/madrobby/scriptaculous/wikis/droppables.

Common options might include:

$options keys Description
$options['accept'] Set to a string or javascript array of strings describing CSS classes that the droppable element will accept. The drop element will only accept elements of the specified CSS classes.
$options['containment'] The droppable element will only accept the dragged element if it is contained in the given elements (element ids). Can be a string or a javascript array of id references.
$options['overlap'] If set to 'horizontal' or 'vertical', the droppable element will only react to a draggable element if it is overlapping the droparea by more than 50% in the given axis.
$options['onDrop'] A javascript call back that is called when the dragged element is dropped on the droppable element.

dropRemote(string $id, array $options)

Makes a drop target that creates an XMLHttpRequest when a draggable element is dropped on it. The $options array for this function are the same as those specified for drop() and link().

7.1.2.11 slider

There is no translation yet for this section. Please help out and translate this.. More information about translations

slider(string $id, string $track_id, array $options)

Creates a directional slider control. For more information see http://wiki.github.com/madrobby/scriptaculous/slider.

Common options might include:

$options keys Description

$options['axis']

Sets the direction the slider will move in. 'horizontal' or 'vertical'. Defaults to horizontal

$options['handleImage']

The id of the image that represents the handle. This is used to swap out the image src with disabled image src when the slider is enabled. Used in conjunction with handleDisabled.

$options['increment']

Sets the relationship of pixels to values. Setting to 1 will make each pixel adjust the slider value by one.

$options['handleDisabled']

The id of the image that represents the disabled handle. This is used to change the image src when the slider is disabled. Used in conjunction handleImage.

$options['change']
$options['onChange']

JavaScript callback fired when the slider has finished moving, or has its value changed. The callback function receives the slider's current value as a parameter.

$options['slide']
$options['onSlide']

JavaScript callback that is called whenever the slider is moved by dragging. It receives the slider's current value as a parameter.

7.1.2.12 editor

There is no translation yet for this section. Please help out and translate this.. More information about translations

editor(string $id, string $url, array $options)

Creates an in-place editor at DOM id. The supplied $url should be an action that is responsible for saving element data. For more information and demos see http://github.com/madrobby/scriptaculous/wikis/ajax-inplaceeditor.

Common options might include:

$options keys Description

$options['collection']

Activate the 'collection' mode of in-place editing. $options['collection'] takes an array which is turned into options for the select. To learn more about collection see http://github.com/madrobby/scriptaculous/wikis/ajax-inplacecollectioneditor.

$options['callback']

A function to execute before the request is sent to the server. This can be used to format the information sent to the server. The signature is function(form, value)

$options['okText']

Text of the submit button in edit mode

$options['cancelText']

The text of the link that cancels editing

$options['savingText']

The text shown while the text is sent to the server

$options['formId']

$options['externalControl']

$options['rows']

The row height of the input field

$options['cols']

The number of columns the text area should span

$options['size']

Synonym for ‘cols’ when using single-line

$options['highlightcolor']

The highlight color

$options['highlightendcolor']

The color which the highlight fades to

$options['savingClassName']

$options['formClassName']

$options['loadingText']

$options['loadTextURL']

Example

<div id="in_place_editor_id">Text To Edit</div>
<?php
echo $ajax->editor( 
    "in_place_editor_id", 
    array( 
        'controller' => 'Posts', 
        'action' => 'update_title',
        $id
    ), 
    array()
);
?>
  1. <div id="in_place_editor_id">Text To Edit</div>
  2. <?php
  3. echo $ajax->editor(
  4. "in_place_editor_id",
  5. array(
  6. 'controller' => 'Posts',
  7. 'action' => 'update_title',
  8. $id
  9. ),
  10. array()
  11. );
  12. ?>

7.1.2.13 sortable

There is no translation yet for this section. Please help out and translate this.. More information about translations

sortable(string $id, array $options)

Makes a list or group of floated objects contained by $id sortable. The options array supports a number of parameters. To find out more about sortable see http://wiki.github.com/madrobby/scriptaculous/sortable.

<div id='sortableContainer'>
	<div id='element_1' class='sortableItem'>
		Element 1
	</div>
	<div id='element_2' class='sortableItem'>
		Element 2
	</div>
	<div id='element_3' class='sortableItem'>
		Element 3
	</div>
</div>
<script type='text/javascript'>
function writeupdate () {
	var id_array = Sortable.sequence('sortableContainer');
	new Ajax.Request('/reports/updatesortorder/'+ id_array.join(','),
						 {
						onSuccess: function() {alert("Order Updated");}
						}
					);
}
</script>
<?php
echo $ajax->sortable('sortableContainer',array('tag'=>'div','only'=>'sortableItem','onUpdate'=>'writeupdate'));
?>
  1. <div id='sortableContainer'>
  2. <div id='element_1' class='sortableItem'>
  3. Element 1
  4. </div>
  5. <div id='element_2' class='sortableItem'>
  6. Element 2
  7. </div>
  8. <div id='element_3' class='sortableItem'>
  9. Element 3
  10. </div>
  11. </div>
  12. <script type='text/javascript'>
  13. function writeupdate () {
  14. var id_array = Sortable.sequence('sortableContainer');
  15. new Ajax.Request('/reports/updatesortorder/'+ id_array.join(','),
  16. {
  17. onSuccess: function() {alert("Order Updated");}
  18. }
  19. );
  20. }
  21. </script>
  22. <?php
  23. echo $ajax->sortable('sortableContainer',array('tag'=>'div','only'=>'sortableItem','onUpdate'=>'writeupdate'));
  24. ?>

Make sure that you do not include the parenthesis on the onUpdate callback, or it will not execute.

Common options might include:

$options keys Description

$options['tag']

Indicates what kind of child elements of the container will be made sortable. Defaults to 'li'.

$options['only']

Allows for further filtering of child elements. Accepts a CSS class.

$options['overlap']

Either 'vertical' or 'horizontal'. Defaults to vertical.

$options['constraint']

Restrict the movement of the draggable elements. accepts 'horizontal' or 'vertical'. Defaults to vertical.

$options['handle']

Makes the created Draggables use handles, see the handle option on Draggables.

$options['onUpdate']

Called when the drag ends and the Sortable's order is changed in any way. When dragging from one Sortable to another, the callback is called once on each Sortable.

$options['hoverclass']

Give the created droppable a hoverclass.

$options['ghosting']

If set to true, dragged elements of the sortable will be cloned and appear as a ghost, instead of directly manipulating the original element.