logo

Sending Ajax requests to ELMA server

It is often necessary to work with data, which users enter when filling in forms or sending messages. Scripts when loading/editing form field values partially solve this problem, however, their functionality is limited, if, for example, you need to handle system properties of objects or perform complex actions, such as starting a business process.

Ajax requests are a powerful tool, which can deal with collecting required data from a form, sending them to the ELMA server, process them and send the resulting data back to the form.

This article illustrates several examples of using Ajax requests.

Example 1. The end date on the task creation form has to be the start date + two business days.

To do so, you have to edit the file TaskEditor.cshtml, located in the folder ELMA3-Standart(Express)\Web\Modules\EleWise.ELMA.BPM.Web.Tasks\Views\Task, as follows.

First, disable the execution of standard Javascript functions, triggered by changing the start date. For this, comment out this string:

elma.SetDateTimeDependenceInputs(’@(Html.IDFor(m => m.StartDate))’, ’@(Html.IDFor(m => m.EndDate))’);

After that, add the following Javascript, which will be triggered when changing the start date:

<script type="text/javascript">
  $(document).ready(function () {   //instruction to the server, that the script has to be executed
 After the form is loaded
    $(’#StartDate’).bind(’change’, function () {  // set the function as an event handler 
When changing the start date value
      var dat = $(’#StartDate’).val().toString();   // get the currently set start date value
 
      $.ajax( {    // create a new Ajax request
             
        traditional: true,   // since simple data is being conveyed
(string, in this case), disable “thorough” transformation. 
To learn more about data transformation, follow this link (http://jquery.page2page.ru/index.php5/%D0%9F%D1%80%D0%B5%D0%BE%D0%B1%D1%80%D0%B0%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D0%B5_%D0%BE%D0%B1%D1%8A%D0%B5%D0%BA%D1%82%D0%BE%D0%B2_%D0%B4%D0%BB%D1%8F_%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8F_%D0%B2_url)
        url: "@(Url.Action("GetEndDate", "TaskExt", new {area = "EleWise.ELMA.TasksExtension.Web" }))",    
// specify the address to send the request to – 
In this case, the GetEndDate() method

of TaskExtController, located in the web module (EleWise.ELMA.TasksExtension.Web) will be invoked
        data: "StartDate=" + dat,    // define the data to transfer in the request body
        dataType: "json",    // specify the type of the data to transfer
        type: "POST",    // specify the request type
        success: function(data) // define the data handler function, 
which will return the controller method, in case of successful execution
        {
          $(’#EndDate_date’).attr("value", data);   
// the GetEndDate method returns the string, which contains the date as dd.mm.yy; 
write it to the end date
        }
        });
      });
    });
</script>

The GetEndDate() method is defined in the web module (EleWise.ELMA.TasksExtension.Web). To learn more about creating a web module, see the following articles: <!--(http://www.elma-bpm.ru/kb/article-97.html) and (http://www.elma-bpm.ru/kb/article-107.html)-->.

public ActionResult GetEndDate(string StartDate) 
// declaration of the method and conveyed parameters
  {
   var date = DateTime.Parse(StartDate); // parse the date from string to DateTime
   if (date != null) // if parsing is successful
   {
    var calendar = Locator.GetServiceNotNull<EleWise.ELMA.Scheduling.IProductionCalendarService>(); 
// load the business calendar
    DateTime endDate = calendar.EvalTargetTime(date, new TimeSpan(2, 0, 0, 0)); 
// add two days to the start date 
    return Json(endDate.ToShortDateString()); // convert the date to the required format (dd.mm.yy),
 serialize (convert to json) and return to the view
   }
   else // if there is error while converting
    return Json(DateTime.Now.ToShortDateString()); // return the current date to the view
  }

Example 2. You can pass data that are more complex to an Ajax request as follows:

<script type="text/javascript">
  $(document).ready(function () {   
//instructions to the server, that the script has to be executed after the form is loaded
    $(’#CommentActionModel_DocumentAttachments_Document_Id’).bind(’valueChange’, function () {  
// set the function as an event handler ,
when adding a new document to the list of attachments
      var dat = $(’#StartDate’).val();   // get the current value of the start date
      var arr = [];    // initialize array
      arr[’date’] = dat;   // write the received start date value to the array
      var docIds = $(’#div-CommentActionModel_DocumentAttachments_Document_Id’).find(’input’);  
// get IDs of documents, attached to the task and write them to the docIds array
      var i = 0;
      if (docIds.length) { // if the array contains elements
        for (i = 0; i < docIds.length; i++) {
          arr[’docIds[’ + i.toString() + ’]’] = docIds[i].value;   
// consequently write them to the array as arr[’docIds[i]’] = value
        }
        arr[’docIds[’ + (i+1).toString() + ’]’] = this.value;    
// write the last added element to the end of the array
      }
      else {   // if no other documents were added
        arr[’docIds[0]’] = this.value;   // write the ID of the added document to the array
      }
 
      $.ajax( {    // create a new ajax request
             
      url: "@(Url.Action("GetEndDate", "TaskExt", new { area = "EleWise.ELMA.TasksExtension.Web" }))",    
// specify the address to send the request to. 
In this case, the GetEndDate() method of TaskExtController, located in the web module
 (EleWise.ELMA.TasksExtension.Web), will be invoked
      data: $.extend({ }, arr),    // define the data to transfer in the request body
      dataType: "json",    // specify the type of the data to transfer
      type: "POST",    // specify the request type
      success: function(data) // define the data handler function, 
which will return the controller method, in case of successful execution
      {
        var jsonData = JSON.stringify(data); 
// convert the data, returned by the controller to a json string
        var newArr = JSON.parse(jsonData); // parse the string – convert it to a regular array
        if (newArr.length) { // if the array is not empty, process the elements
          for (i = 0; i < newArr.length; i++) {
            // process array element
          }
        } 
      }
      });
    });
  });
</script>

In this case, the code of the controller method is as follows:

public ActionResult GetEndDate(Nullable<DateTime> date, long[] docIds) 
// declaration of the method and conveyed parameters;
 the date is converted to the required type by the controller,
 and the document IDs array is converted to a long-type enumeration
{
 // here data can be processed in the necessary way, 
to test it, add a part of received data to the list and return it back to the form
 List<string> output = new List<string>(); // initialize the list
 output.Add(date.Value.ToString()); // write elements
 output.Add(docIds.ElementAt(0).ToString());
 return Json(output); // convert the list to json and return it to the form
}
Attention
For the data to be received by the controller correctly, element names in JSON couples have to coincide with the names of input parameters in the controller.

 You can download examples of Ajax requests here: http://dl.elma-bpm.ru/Primery.zip