Waffle Recipes

How-To's and Tutorials for the ActiveWAFL Framework

How to Submit a Form Asynchronously via AJAX/API

Posted Nov 19, 2014

Posting a form to an API handler is similar to sending other information to an API Handler.
The general steps are as follows:

  1. Define the API call in APICalls.syrp
  2. Add a server-side API Handler file (or use an existing one) and add an API Handler function
  3. Create an HTML form that collects the data you wish to submit to the API
  4. Handle the form's submit event and, instead of reloading the page, send the form to the API
  5. Handle the response sent back from the API

In Javascript, you can post forms asynchronously to your application's API using the following signature:

Asynchronous Form Submit Function Signature
  1. ____(String call, FormElement form, [Function callbackMethod, String sendToken, Boolean useDefaultJsonParser])
The symbol being used as the function name is ____ (four underscores)

Asynchronous Form Post Example

Define the API Call - Config/More/APICalls.syrp
  1. MyApiCall
  2.     ApiCall             =   ApiGroup1.MyApiCall
  3.     HandlerFunction     =   MyApiCall
  4.     HandlerFile         =   ApiGroup1.php
  5.     HandlerClass        =   \\MyApp\\ApiHandlers\\ApiGroup1
Add a Server Side API Handler - MyApp/ApiHandlers/ApiGroup1.php
  1. <?php
  2. namespace MyApp\ApiHandlers;
  3. class ApiGroup1
  4. {
  5.    static function MyApiCall($args)
  6.    {
  7.         return new \DblEj\Communication\Ajax\AjaxResult("This is a text result for an API call");
  8.     }
  9. }
Create an HTML Form - Example.tpl
  1. <form id="MyForm">
  2.     <label for="SomeInput1">Some Input 1</label>
  3.     <input type="text" id="SomeInput1" name="SomeInput1" />
  5.     <label for="SomeInput2">Some Input 2</label>
  6.     <input type="text" id="SomeInput2" name="SomeInput2" />
  7.     <button type="submit">Submit Form</button>
  8. </form>
Call the API from a Client Side Controller and Handle the Response - Example.js
  1. $("MyForm").AddSubmitHandler(
  2.         function(event)
  3.         {
  4.             //stop the form from loading a new page
  5.             DblEj.EventHandling.Events.StopeEventPropagation(event);
  6.             DblEj.EventHandling.Events.PreventDefaultEvent(event);
  8.             //send the form to the API
  9.             ____("ApiGroup1.MyApiCall", $("MyForm"),
  10.                 function(responseObject)
  11.                 {
  12.                     //the response sent from the API will be in the responseObject
  13.                     console.log("The ApiGroup1.MyApiCall API returned the following response from the form upload");
  14.                     console.log(responseObject);
  15.                 });
  16.         });