1 // https://civicrm.org/licensing
3 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface
4 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Ajax+Pages+and+Forms
6 (function($, CRM
, _
, undefined) {
9 * @param string|object query
10 * @param string mode - optionally specify "front" or "back"
13 CRM
.url = function (path
, query
, mode
) {
14 if (typeof path
=== 'object') {
19 CRM
.console('error', 'Error: CRM.url called before initialization');
22 mode
= CRM
.config
&& CRM
.config
.isFrontend
? 'front' : 'back';
25 var frag
= path
.split('?');
26 var url
= tplURL
[mode
].replace("civicrm-placeholder-url-path", frag
[0]);
29 url
= url
.replace(/[?&]civicrm-placeholder-url-query=1/, '');
32 url
= url
.replace("civicrm-placeholder-url-query=1", typeof query
=== 'string' ? query
: $.param(query
));
35 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + frag
[1];
40 $.fn
.crmURL = function () {
41 return this.each(function() {
43 this.href
= CRM
.url(this.href
);
48 // result is an array, but in js, an array is also an object
49 // Assign all the metadata properties to it, mirroring the results arrayObject in php
50 function arrayObject(data
) {
51 var result
= data
.values
|| [];
52 if (_
.isArray(result
)) {
54 _
.assign(result
, data
);
59 CRM
.api4 = function(entity
, action
, params
, index
) {
60 return new Promise(function(resolve
, reject
) {
61 if (typeof entity
=== 'string') {
62 $.post(CRM
.url('civicrm/ajax/api4/' + entity
+ '/' + action
), {
63 params
: JSON
.stringify(params
),
66 .done(function (data
) {
67 resolve(arrayObject(data
));
69 .fail(function (data
) {
70 reject(data
.responseJSON
);
73 $.post(CRM
.url('civicrm/ajax/api4'), {
74 calls
: JSON
.stringify(entity
)
76 .done(function(data
) {
77 _
.each(data
, function(item
, key
) {
78 data
[key
] = arrayObject(item
);
82 .fail(function (data
) {
83 reject(data
.responseJSON
);
91 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface#AJAXInterface-CRM.api3
93 CRM
.api3 = function(entity
, action
, params
, status
) {
94 if (typeof(entity
) === 'string') {
97 action
: action
.toLowerCase(),
98 json
: JSON
.stringify(params
|| {})
104 json
: JSON
.stringify(entity
)
109 url
: CRM
.url('civicrm/ajax/rest'),
112 type
: params
.action
.indexOf('get') === 0 ? 'GET' : 'POST'
115 // Default status messages
116 if (status
=== true) {
117 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
118 if (params
.action
.indexOf('get') === 0) {
119 status
.start
= ts('Loading...');
120 status
.success
= null;
123 var messages
= status
=== true ? {} : status
;
124 CRM
.status(status
, ajax
);
133 CRM
.api = function(entity
, action
, params
, options
) {
137 success: function(result
, settings
) {
140 error: function(result
, settings
) {
141 $().crmError(result
.error_message
, ts('Error'));
144 callBack: function(result
, settings
) {
145 if (result
.is_error
== 1) {
146 return settings
.error
.call(this, result
, settings
);
148 return settings
.success
.call(this, result
, settings
);
150 ajaxURL
: 'civicrm/ajax/rest'
152 action
= action
.toLowerCase();
153 // Default success handler
159 settings
.success = function() {
160 CRM
.status(ts('Saved'));
165 settings
.success = function() {
166 CRM
.status(ts('Removed'));
173 json
: JSON
.stringify(params
)
175 // Pass copy of settings into closure to preserve its value during multiple requests
178 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
181 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
182 success: function(result
) {
183 stg
.callBack
.call(stg
.context
, result
, stg
);
186 })($.extend({}, settings
, options
));
189 $.widget('civi.crmSnippet', {
195 _originalContent
: null,
197 isOriginalUrl: function() {
201 newUrl
= this._formatUrl(this.options
.url
),
202 oldUrl
= this._formatUrl(this._originalUrl
);
204 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
208 $.each((newUrl
.split('?')[1] || '').split('&'), function(k
, v
) {
209 var arg
= v
.split('=');
210 args
[arg
[0]] = arg
[1];
212 $.each((oldUrl
.split('?')[1] || '').split('&'), function(k
, v
) {
213 var arg
= v
.split('=');
214 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
220 resetUrl: function() {
221 this.options
.url
= this._originalUrl
;
223 _create: function() {
224 this.element
.addClass('crm-ajax-container');
225 if (!this.element
.is('.crm-container *')) {
226 this.element
.addClass('crm-container');
228 this._handleOrderLinks();
229 // Set default if not supplied
230 this.options
.url
= this.options
.url
|| document
.location
.href
;
231 this._originalUrl
= this.options
.url
;
233 _onFailure: function(data
, status
) {
234 var msg
, title
= ts('Network Error');
235 if (this.options
.block
) this.element
.unblock();
236 this.element
.trigger('crmAjaxFail', data
);
239 title
= ts('Access Denied');
240 msg
= ts('Ensure you are still logged in and have permission to access this feature.');
243 msg
= ts('Unable to reach the server. Please refresh this page in your browser and try again.');
245 CRM
.alert(msg
, title
, 'error');
247 _onError: function(data
) {
248 this.element
.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data
);
249 if (this.options
.crmForm
&& this.options
.crmForm
.autoClose
&& this.element
.data('uiDialog')) {
250 this.element
.dialog('close');
253 _formatUrl: function(url
, snippetType
) {
255 url
= url
.split('#')[0];
256 // Add snippet argument to url
258 if (url
.search(/[&?]snippet=/) < 0) {
259 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=' + snippetType
;
261 url
= url
.replace(/snippet=[^&]*/, 'snippet=' + snippetType
);
266 // Hack to deal with civicrm legacy sort functionality
267 _handleOrderLinks: function() {
269 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
270 if (that
.options
.block
) that
.element
.block();
271 $.getJSON(that
._formatUrl(this.href
, 'json')).done(function() {
274 e
.stopImmediatePropagation();
278 refresh: function() {
280 var url
= this._formatUrl(this.options
.url
, 'json');
281 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
282 if (this.options
.block
) this.element
.block();
283 $.getJSON(url
, function(data
) {
284 if (data
.status
=== 'redirect') {
285 that
.options
.url
= data
.userContext
;
286 return that
.refresh();
288 if (that
.options
.block
) that
.element
.unblock();
289 if (!$.isPlainObject(data
)) {
290 that
._onFailure(data
);
293 if (data
.status
=== 'error') {
298 that
.element
.trigger('crmUnload').trigger('crmBeforeLoad', data
);
299 that
._beforeRemovingContent();
300 that
.element
.html(data
.content
);
301 that
._handleOrderLinks();
302 that
.element
.trigger('crmLoad', data
);
303 if (that
.options
.crmForm
) that
.element
.trigger('crmFormLoad', data
);
304 // This is only needed by forms that load via ajax but submit without ajax, e.g. configure contribution page tabs
305 // TODO: remove this when those forms have been converted to use ajax submit
306 if (data
.status
=== 'form_error' && $.isPlainObject(data
.errors
)) {
307 that
.element
.trigger('crmFormError', data
);
308 $.each(data
.errors
, function(formElement
, msg
) {
309 $('[name="'+formElement
+'"]', that
.element
).crmError(msg
);
312 }).fail(function(data
, msg
, status
) {
313 that
._onFailure(data
, status
);
316 // Perform any cleanup needed before removing/replacing content
317 _beforeRemovingContent: function() {
319 // Save original content to be restored if widget is destroyed
320 if (this._originalContent
=== null) {
321 $('.blockUI', this.element
).remove();
322 this._originalContent
= this.element
.contents().detach();
324 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
326 _destroy: function() {
327 this.element
.removeClass('crm-ajax-container').trigger('crmUnload');
328 this._beforeRemovingContent();
329 if (this._originalContent
!== null) {
330 this.element
.empty().append(this._originalContent
);
336 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
338 CRM
.loadPage = function(url
, options
) {
340 target
: '#crm-ajax-dialog-' + (dialogCount
++),
341 dialog
: (options
&& options
.target
) ? false : {}
343 if (options
) $.extend(true, settings
, options
);
346 if (settings
.dialog
) {
347 settings
.dialog
= CRM
.utils
.adjustDialogDefaults(settings
.dialog
);
348 $('<div id="' + settings
.target
.substring(1) + '"></div>')
349 .dialog(settings
.dialog
)
350 .parent().find('.ui-dialog-titlebar')
351 .append($('<a class="crm-dialog-titlebar-print ui-dialog-titlebar-close" title="'+ts('Print window')+'" target="_blank" style="right:3.8em;"/>')
352 .button({icons
: {primary
: 'fa-print'}, text
: false}));
354 // Add handlers to new or existing dialog
355 if ($(settings
.target
).data('uiDialog')) {
357 .on('dialogclose', function() {
358 if (settings
.dialog
&& $(this).attr('data-unsaved-changes') !== 'true') {
359 $(this).crmSnippet('destroy').dialog('destroy').remove();
362 .on('crmLoad', function(e
, data
) {
364 if (e
.target
=== $(settings
.target
)[0] && data
&& !settings
.dialog
.title
&& data
.title
) {
365 $(this).dialog('option', 'title', data
.title
);
368 $(this).parent().find('a.crm-dialog-titlebar-print').attr('href', $(this).data('civiCrmSnippet')._formatUrl($(this).crmSnippet('option', 'url'), '2'));
371 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
372 return $(settings
.target
);
374 CRM
.loadForm = function(url
, options
) {
375 var formErrors
= [], settings
= {
380 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
381 cancelButton
: '.cancel',
382 openInline
: 'a.open-inline, a.button, a.action-item, a.open-inline-noreturn',
383 onCancel: function(event
) {}
386 // Move options that belong to crmForm. Others will be passed through to crmSnippet
387 if (options
) $.each(options
, function(key
, value
) {
388 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
389 settings
.crmForm
[key
] = value
;
392 settings
[key
] = value
;
396 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
398 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
399 function cancelAction() {
400 var dirty
= CRM
.utils
.initialValueChanged($('form:not([data-warn-changes=false])', widget
));
401 widget
.attr('data-unsaved-changes', dirty
? 'true' : 'false');
403 var id
= widget
.attr('id') + '-unsaved-alert',
404 title
= widget
.dialog('option', 'title'),
405 alert
= CRM
.alert('<p>' + ts('%1 has not been saved.', {1: title
}) + '</p><p><a href="#" id="' + id
+ '">' + ts('Restore') + '</a></p>', ts('Unsaved Changes'), 'alert unsaved-dialog', {expires
: 60000});
406 $('#' + id
).button({icons
: {primary
: 'fa-undo'}}).click(function(e
) {
407 widget
.attr('data-unsaved-changes', 'false').dialog('open');
413 if (widget
.data('uiDialog')) widget
.on('dialogbeforeclose', function(e
) {
414 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
415 if (e
.originalEvent
) {
420 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
421 var $el
= $(this).attr('data-unsaved-changes', 'false'),
422 settings
= $el
.crmSnippet('option', 'crmForm');
423 if (settings
.cancelButton
) $(settings
.cancelButton
, this).click(function(e
) {
425 var returnVal
= settings
.onCancel
.call($el
, e
);
426 if (returnVal
!== false) {
427 $el
.trigger('crmFormCancel', e
);
428 if ($el
.data('uiDialog') && settings
.autoClose
) {
432 else if (!settings
.autoClose
) {
433 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
437 if (settings
.validate
) {
438 $("form", this).crmValidate();
440 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
441 url
: data
.url
.replace(/reset=1[&]?/, ''),
443 success: function(response
) {
444 if (response
.content
=== undefined) {
445 $el
.trigger('crmFormSuccess', response
);
446 // Reset form for e.g. "save and new"
447 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
448 // Force reset of original url
449 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
450 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
452 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
453 else if ($el
.data('uiDialog') && (settings
.autoClose
|| response
.action
=== 8)) {
456 else if (settings
.autoClose
=== false) {
457 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
461 if ($el
.crmSnippet('option', 'block')) $el
.unblock();
462 response
.url
= data
.url
;
463 $el
.html(response
.content
).trigger('crmLoad', response
).trigger('crmFormLoad', response
);
464 if (response
.status
=== 'form_error') {
466 $el
.trigger('crmFormError', response
);
467 $.each(response
.errors
|| [], function(formElement
, msg
) {
468 formErrors
.push($('[name="'+formElement
+'"]', $el
).crmError(msg
));
473 beforeSubmit: function(submission
) {
474 $.each(formErrors
, function() {
475 if (this && this.close
) this.close();
477 if ($el
.crmSnippet('option', 'block')) $el
.block();
478 $el
.trigger('crmFormSubmit', submission
);
480 }, settings
.ajaxForm
));
481 if (settings
.openInline
) {
482 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
483 $(this).off('.openInline').on('click.openInline', settings
.openInline
, function(e
) {
484 if ($(this).is(exclude
+ ', .crm-popup')) {
487 if ($(this).hasClass('open-inline-noreturn')) {
488 // Force reset of original url
489 $el
.data('civiCrmSnippet')._originalUrl
= $(this).attr('href');
491 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
495 if ($el
.data('uiDialog')) {
496 // Show form buttons as part of the dialog
497 var buttonContainers
= '.crm-submit-buttons, .action-link',
500 $(buttonContainers
, $el
).find('input.crm-form-submit, a.button, button').each(function() {
502 label
= $el
.is('input') ? $el
.attr('value') : $el
.text(),
503 identifier
= $el
.attr('name') || $el
.attr('href');
504 if (!identifier
|| identifier
=== '#' || $.inArray(identifier
, added
) < 0) {
505 var $icon
= $el
.find('.icon, .crm-i'),
506 button
= {'data-identifier': identifier
, text
: label
, click: function() {
510 button
.icons
= {primary
: $icon
.attr('class')};
512 var action
= $el
.attr('crm-icon') || ($el
.hasClass('cancel') ? 'fa-times' : 'fa-check');
513 button
.icons
= {primary
: action
};
515 buttons
.push(button
);
516 added
.push(identifier
);
518 // display:none causes the form to not submit when pressing "enter"
519 $el
.parents(buttonContainers
).css({height
: 0, padding
: 0, margin
: 0, overflow
: 'hidden'}).find('.crm-button-icon').hide();
521 $el
.dialog('option', 'buttons', buttons
);
523 // Allow a button to prevent ajax submit
524 $('input[data-no-ajax-submit=true]').click(function() {
525 $(this).closest('form').ajaxFormUnbind();
527 // For convenience, focus the first field
528 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
533 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
535 CRM
.popup = function(e
) {
536 var $el
= $(this).first(),
537 url
= $el
.attr('href'),
538 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
539 settings
= $el
.data('popup-settings') || {},
541 settings
.dialog
= settings
.dialog
|| {};
542 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
+ ', .open-inline, .open-inline-noreturn')) {
545 // Sized based on css class
546 if ($el
.hasClass('small-popup')) {
547 settings
.dialog
.width
= 400;
548 settings
.dialog
.height
= 300;
550 else if ($el
.hasClass('medium-popup')) {
551 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
553 var dialog
= popup(url
, settings
);
554 // Trigger events from the dialog on the original link element
555 $el
.trigger('crmPopupOpen', [dialog
]);
556 // Listen for success events and buffer them so we only trigger once
557 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function(e
, data
) {
560 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
562 $el
.trigger('crmPopupFormSuccess', [dialog
, formData
]);
564 $el
.trigger('crmPopupClose', [dialog
, data
]);
569 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
570 * @param e {event|selector}
572 CRM
.refreshParent = function(e
) {
573 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
574 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
575 $table
= $el
.closest('.dataTable');
576 // Call native refresh method on ajax datatables
577 if ($table
.length
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
578 // Refresh ALL datatables - needed for contact relationship tab
579 $.each($.fn
.dataTable
.fnTables(), function() {
580 if ($(this).dataTable().fnSettings().sAjaxSource
) $(this).unblock().dataTable().fnDraw();
583 // Otherwise refresh the nearest crmSnippet
585 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
591 .on('click', 'a.crm-popup', CRM
.popup
)
592 // Close unsaved dialog messages
593 .on('dialogopen', function(e
) {
594 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
596 // Destroy old unsaved dialog
597 .on('dialogcreate', function(e
) {
598 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
600 // Ensure wysiwyg content is updated prior to ajax submit
601 .on('form-pre-serialize', function(e
) {
602 $('.crm-wysiwyg-enabled', e
.target
).each(function() {
603 CRM
.wysiwyg
.updateElement(this);
606 // Auto-resize dialogs when loading content
607 .on('crmLoad dialogopen', 'div.ui-dialog.ui-resizable.crm-container', function(e
) {
610 $dialog
= $wrapper
.children('.ui-dialog-content');
611 // small delay to allow contents to render
612 window
.setTimeout(function() {
613 var currentHeight
= $wrapper
.outerHeight(),
614 padding
= currentHeight
- $dialog
.height(),
615 newHeight
= $dialog
.prop('scrollHeight') + padding
,
616 menuHeight
= $('#civicrm-menu').outerHeight();
617 if ($('body').hasClass('crm-menubar-below-cms-menu')) {
618 menuHeight
+= $('#civicrm-menu').offset().top
;
620 var maxHeight
= $(window
).height() - menuHeight
;
621 newHeight
= newHeight
> maxHeight
? maxHeight
: newHeight
;
622 if (newHeight
> (currentHeight
+ 15)) {
623 $dialog
.dialog('option', {
624 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},