Skip to content

Instantly share code, notes, and snippets.

@lonalore
Last active June 14, 2017 12:31
Show Gist options
  • Save lonalore/92447e7f91fd88da16b1fa59d40c1215 to your computer and use it in GitHub Desktop.
Save lonalore/92447e7f91fd88da16b1fa59d40c1215 to your computer and use it in GitHub Desktop.

Ajax API - Ajax Forms in e107

Ajax-enabled forms in e107 offer dynamic form behavior with no page reloads and are easy to create and manipulate. They are a simple extension of the e107 Form API.

What is dynamic behavior? Traditional web behavior has the user fill in a form, click a button, and the entire page is rebuilt and sent back to the browser. Ajax-enabled forms update or replace part of the page or part of the form without doing a full page reload - only the part that needs to be changed is changed. It's more responsive to the user and typically faster than the traditional page reload approach.

Some facts about Ajax:

  • Ajax forms provide dynamic form behavior without page reloads.
  • As a developer you don't use or touch any JavaScript to create an Ajax-enabled form. E107 does all the work for you.
  • Most of the time, Ajax-enabled forms are just dynamic replacement of an HTML region on the page, which is most often a piece of a rebuilt form.

The Basics

To create an Ajax-enabled form:

  • Mark a form element as Ajax-enabled using the .e-ajax class and configure it using data-* attributes. This form element will now trigger a background Ajax call when it is changed or clicked.

On the server side: retrieving the data

Whichever HTTP method (POST/GET) you choose, the server receives a string that will be parsed in order to get the data as a list of key/value pairs. The request will contain not only the form element data, but also data of the entire form.

On the client side: response handler

Two kinds of response types are supported:

  • Text/HTML formatted response: using this type, you need to set data-target and data-method attributes on the form element fired ajax event (see below).
  • JSON formatted response: provides the user the ability to execute multiple commands in one response. For example, if you use the Ajax Framework to generate response message (see below).

Examples

Form with ajax-enabled textfield

$tp = e107::getParser();
$form = e107::getForm();
$image = $tp ->toGlyph('fa-spin');

$html = $form->open('test-form', 'post', e_SELF);

$vars = array(
	'name'    => 'ajax-example-textfield',
	'value'   => '',
	'size'   => 80,
	'options' => array(
		'class'   => 'e-ajax form-control',
		// The JavaScript event to respond to. This is normally selected automatically
		// for the type of form widget being used, and is only needed if you need to
		// override the default behavior.
		'data-event' => 'keyup',
		// URL for Ajax request.
		'data-src' => e_SELF,
		// (Optional) Ajax type: POST or GET. Default is POST.
		'data-ajax-type' => 'POST',
		// (Optional) Target container for result. CSS selector. If it is not set, default
		// will be the element fired the event.
		'data-target' => '.target-container',
		// (Optional) Method: 'replaceWith', 'append', 'prepend', 'before', 'after', 'html'.
		'data-method' => 'html',
		// (Optional) Image to show loading.
		'data-loading' => $tp->toAttribute($image),
	),
);

$html .= $form->text($vars['name'], $vars['value'], $vars['size'], $vars['options']);
$html .= $form->close();

Form with ajax-enabled select list

$tp = e107::getParser();
$form = e107::getForm();
$image = $tp ->toGlyph('fa-spin');

$html = $form->open('test-form', 'post', e_SELF);

$vars = array(
	'name'    => 'ajax-example-select',
	'values'   => array(
		'foo' => 'bar',
		'bar' => 'foo',
	),
	'selected' => false,
	'options' => array(
		'class'   => 'e-ajax form-control',
		// The JavaScript event to respond to. This is normally selected automatically
		// for the type of form widget being used, and is only needed if you need to
		// override the default behavior.
		'data-event' => 'change',
		// URL for Ajax request.
		'data-src' => e_SELF,
		// (Optional) Ajax type: POST or GET. Default is POST.
		'data-ajax-type' => 'POST',
		// (Optional) Target container for result. CSS selector. If it is not set, default
		// will be the element fired the event.
		'data-target' => '.target-container',
		// (Optional) Method: 'replaceWith', 'append', 'prepend', 'before', 'after', 'html'.
		'data-method' => 'html',
		// (Optional) Image to show loading.
		'data-loading' => $tp->toAttribute($image),
	),
	'default' => 'bar',
);

$html .= $form->select($vars['name'], $vars['values'], $vars['selected'], $vars['options'], $vars['default']);
$html .= $form->close();

Ajax-enabled form element on Admin UI

/**
 * Class PLUGIN_ADMIN_ui.
 */
class PLUGIN_ADMIN_ui extends e_admin_ui
{

	// ... your code ...

	/**
	 * @var array UI field data.
	 */
	protected $fields = array(
		
		// ... fields ...

		'ajax_example_field'      => array(
			'title'      => 'Some title',
			'type'       => 'dropdown',
			'width'      => 'auto',
			'readonly'   => false,
			'inline'     => false,
			'filter'     => true,
			'writeParms' => array(
				'ajax' => array(
					// Target container for result.
					'target'  => '#target-container',
					// URL for Ajax request.
					'src'     => '', // Value is set in init() function.
					// Method: 'replaceWith', 'append', 'prepend', 'before', 'after', 'html'.
					'method'  => 'replaceWith',
					// Image to show loading.
					'loading' => '', // Value is set in init() function.
				),
			),
			'thclass'    => 'center',
			'class'      => 'center',
			'tab'        => 0,
		),

		// ... fields ...

	);

	/**
	 * User defined init.
	 */
	public function init()
	{
		// Set Ajax options.
		$this->fields['ajax_example_field']['writeParms']['ajax']['src'] = e_SELF . '?mode=ajax&action=bar';
		$this->fields['ajax_example_field']['writeParms']['ajax']['loading'] = '<img src="' . e_PLUGIN_ABS . 'path/to/images/clock.svg" />';
	}
}

You can see a fully working example in this file: admin_config.php

E107's Ajax framework

E107's Ajax framework is used to dynamically update parts of a page's HTML based on data from the server. Upon a specified event, such as a button click, a callback function is triggered which performs server-side logic and may return updated markup, which is then replaced on-the-fly with no page refresh necessary.

Ajax framework creates a PHP macro language that allows the server to instruct JavaScript to perform actions on the client browser.

When responding to Ajax requests, the server should do what it needs to do for that request, then create a commands array. This commands array will be converted to a JSON object and returned to the client, which will then iterate over the array and process it like a macro language.

Each command item is an associative array which will be converted to a command object on the JavaScript side. $command_item['command'] is the type of command, e.g. 'alert' or 'replace'. The command array may contain any other data that the command needs to process, e.g. 'method', 'target', 'settings', etc.

Commands are usually created with a couple of helper functions, so they look like this:

$ajax = e107::ajax();

$commands = array();
// Merge array into e107.settings javascript object.
$commands[] = $ajax->commandSettings(array('foo' => 'bar'));
// Remove 'disabled' attribute from the '#object-1' element.
$commands[] = $ajax->commandInvoke('#object-1', 'removeAttr', array('disabled'));
// Insert HTML content into the '#object-1' element.
$commands[] = $ajax->commandInsert('#object-1', 'html', 'some html content');

// This method echos data in JSON format. It sets the header for JavaScript output.
$ajax->response($commands);

Ajax framework commands

response

This function should be used for JavaScript callback functions to echo data in JSON format. It sets the header for JavaScript output.

$ajax = e107::ajax();
$ajax->response($var);

Parameters

$var (optional) If set, the variable will be converted to JSON and output.

commandAlert

The 'alert' command instructs the client to display a JavaScript alert dialog box.

$ajax = e107::ajax();
$ajax->commandAlert($text);

Parameters

$text The message string to display to the user.

Return value

An array suitable for use with the e107::ajax()->render() function.

commandInsert

This command instructs the client to insert the given HTML.

$ajax = e107::ajax();
$ajax->commandInsert($target, $method, $html);

Parameters

$target A jQuery target selector.

$method Selected method fo DOM manipulation: 'replaceWith', 'append', 'prepend', 'before', 'after', 'html'

$html The data to use with the jQuery method.

Return value

An array suitable for use with the e107::ajax()->render() function.

commandRemove

The 'remove' command instructs the client to use jQuery's remove() method to remove each of elements matched by the given target, and everything within them.

$ajax = e107::ajax();
$ajax->commandRemove($target);

Parameters

$target A jQuery target selector.

Return value

An array suitable for use with the e107::ajax()->render() function.

See also

http://docs.jquery.com/Manipulation/remove#expr

commandCSS

The 'css' command will instruct the client to use the jQuery css() method to apply the CSS arguments to elements matched by the given target.

$ajax = e107::ajax();
$ajax->commandCSS($target, $argument);

Parameters

$target A jQuery target selector.

$argument An array of key/value pairs to set in the CSS for the target.

Return value

An array suitable for use with the e107::ajax()->render() function.

See also

http://docs.jquery.com/CSS/css#properties

commandSettings

The 'settings' command instructs the client to extend e107.settings with the given array.

$ajax = e107::ajax();
$ajax->commandSettings($settings);

Parameters

$settings An array of key/value pairs to add to the settings. This will be utilized for all commands after this if they do not include their own settings array.

Return value

An array suitable for use with the e107::ajax()->render() function.

commandData

The 'data' command instructs the client to attach the name=value pair of data to the target via jQuery's data cache.

$ajax = e107::ajax();
$ajax->commandData($target, $name, $value);

Parameters

$target A jQuery selector string.

$name The name or key (in the key value pair) of the data attached to this target.

$value The value of the data. Not just limited to strings can be any format.

Return value

An array suitable for use with the e107::ajax()->render() function.

See also

http://docs.jquery.com/Core/data#namevalue

commandInvoke

The 'invoke' command will instruct the client to invoke the given jQuery method with the supplied arguments on the elements matched by the given target. Intended for simple jQuery commands, such as attr(), addClass(), removeClass(), toggleClass(), etc.

$ajax = e107::ajax();
$ajax->commandInvoke($target, $method, $arguments);

Parameters

$target A jQuery selector string.

$method The jQuery method to invoke.

$arguments (optional) A list of arguments to the jQuery $method, if any.

Return value

An array suitable for use with the e107::ajax()->render() function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment