Merge in 5.26
[civicrm-core.git] / js / crm.ajax.js
index efbcf2c1e35f875d979df2fd686d5a9635b280e2..bfff407843dc2e02e4723c866e431ecc48d8854d 100644 (file)
@@ -3,7 +3,7 @@
  * @see https://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface
  * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Ajax+Pages+and+Forms
  */
-(function($, CRM, undefined) {
+(function($, CRM, _, undefined) {
   /**
    * @param string path
    * @param string|object query
     });
   };
 
+  // result is an array, but in js, an array is also an object
+  // Assign all the metadata properties to it, mirroring the results arrayObject in php
+  function arrayObject(data) {
+    var result = data.values || [];
+    if (_.isArray(result)) {
+      delete(data.values);
+      _.assign(result, data);
+    }
+    return result;
+  }
+
+  CRM.api4 = function(entity, action, params, index) {
+    return new Promise(function(resolve, reject) {
+      if (typeof entity === 'string') {
+        $.post(CRM.url('civicrm/ajax/api4/' + entity + '/' + action), {
+          params: JSON.stringify(params),
+          index: index
+        })
+          .done(function (data) {
+            resolve(arrayObject(data));
+          })
+          .fail(function (data) {
+            reject(data.responseJSON);
+          });
+      } else {
+        $.post(CRM.url('civicrm/ajax/api4'), {
+          calls: JSON.stringify(entity)
+        })
+          .done(function(data) {
+            _.each(data, function(item, key) {
+              data[key] = arrayObject(item);
+            });
+            resolve(data);
+          })
+          .fail(function (data) {
+            reject(data.responseJSON);
+          });
+      }
+    });
+  };
+
   /**
    * AJAX api
    * @link http://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface#AJAXInterface-CRM.api3
         var buttonContainers = '.crm-submit-buttons, .action-link',
           buttons = [],
           added = [];
-        $(buttonContainers, $el).find('input.crm-form-submit, a.button').each(function() {
+        $(buttonContainers, $el).find('input.crm-form-submit, a.button, button').each(function() {
           var $el = $(this),
             label = $el.is('input') ? $el.attr('value') : $el.text(),
             identifier = $el.attr('name') || $el.attr('href');
       });
   });
 
-}(jQuery, CRM));
+}(jQuery, CRM, _));