Developer Area/Core Subsystems/Form API (Pieforms)/Form APIAJAXForms

From Mahara Wiki
Jump to: navigation, search

The form API supports submission of forms to a hidden iframe (not really AJAX but as I'm writing new documentation elsewhere I can't be bothered renaming this page), just by toggling a single field and changing the 'formname_submit' function to output JSON instead of redirect the user. This makes forms very responsive.

Form submission using JS

If you want the form to be submitted to the server without a page reload, then all you need to do is set 'jsform' to true, and make sure your formname_submit function echos JSON and exits, as in this example:

$f = array(
'name' => 'editsitepage',
'method' => 'post',
'jsform' => true,
'jssuccessfunction' => 'contentSaved',
'action' => '',
'elements' => array(
'pagename' => array(
'type' => 'text',
'title' => get_string('pagename'),
'value' => '',
'pagetext' => array(
'name' => 'pagetext',
'type' => 'textarea',
'rows' => 20,
'cols' => 80,
'title' => get_string('pagetext'),
'value' => '',
'rules' => array(
'required' => true
'submit' => array(
'value' => get_string('savechanges'),
'type'  => 'submit',

With jsform set to true, the form handler will create a javascript function that posts the form content to the 'action' target. Normally, you can just leave 'action' blank, as this will submit the data to the page where the form is defined.

The formname_submit function is expected to process the request as normal, and then output JSON to describe the result. The format of this JSON is subject to change, however at the moment it is an array with the following fields
 :* an 'error' field set to either
    • false, if there are no errors, or
    • 'local', if the error is local to this callback, or
    • some other machine readable code for potentially global errors; and
  • a 'message' field set to an appropriate message.

'local' error messages will be displayed near the form's submit button (as decided by the renderer). Other errors are passed to the global error handler defined in mahara.js. (todo: this may not be implemented at this time - bug nigel if/when you need it)

The function json_reply($error, $message) will set the appropriate headers and send the json encoded array with the error and message fields set, for example,

function fooform_submit(Pieform $form, $values) {
set_config('foo', $values['foo']);
$form->json_reply(PIEEFORM_OK, get_string('setfoosuccessfully'));

If the submission was successful, then the js function named in 'jssuccesscallback' will be called. 'jsfailurecallback' is also available, should you need it.