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("*path*", frag
[0]);
29 url
= url
.replace(/[?&]\*query\*/, '');
32 url
= url
.replace("*query*", typeof query
=== 'string' ? query
: $.param(query
));
35 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + frag
[1];
42 function (p
, params
) {
43 CRM
.console('warn', 'Calling crmURL from jQuery is deprecated. Please use CRM.url() instead.');
44 return CRM
.url(p
, params
);
48 $.fn
.crmURL = function () {
49 return this.each(function() {
51 this.href
= CRM
.url(this.href
);
59 CRM
.api3 = function(entity
, action
, params
, status
) {
60 if (typeof(entity
) === 'string') {
63 action
: action
.toLowerCase(),
64 json
: JSON
.stringify(params
|| {})
70 json
: JSON
.stringify(entity
)
75 url
: CRM
.url('civicrm/ajax/rest'),
78 type
: params
.action
.indexOf('get') < 0 ? 'POST' : 'GET'
81 // Default status messages
82 if (status
=== true) {
83 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
84 if (params
.action
.indexOf('get') === 0) {
85 status
.start
= ts('Loading...');
86 status
.success
= null;
89 var messages
= status
=== true ? {} : status
;
90 CRM
.status(status
, ajax
);
99 CRM
.api = function(entity
, action
, params
, options
) {
103 success: function(result
, settings
) {
106 error: function(result
, settings
) {
107 $().crmError(result
.error_message
, ts('Error'));
110 callBack: function(result
, settings
) {
111 if (result
.is_error
== 1) {
112 return settings
.error
.call(this, result
, settings
);
114 return settings
.success
.call(this, result
, settings
);
116 ajaxURL
: 'civicrm/ajax/rest'
118 action
= action
.toLowerCase();
119 // Default success handler
125 settings
.success = function() {
126 CRM
.status(ts('Saved'));
131 settings
.success = function() {
132 CRM
.status(ts('Removed'));
139 json
: JSON
.stringify(params
)
141 // Pass copy of settings into closure to preserve its value during multiple requests
144 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
147 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
148 success: function(result
) {
149 stg
.callBack
.call(stg
.context
, result
, stg
);
152 })($.extend({}, settings
, options
));
156 * Backwards compatible with jQuery fn
159 $.fn
.crmAPI = function(entity
, action
, params
, options
) {
160 CRM
.console('warn', 'Calling crmAPI from jQuery is deprecated. Please use CRM.api3() instead.');
161 return CRM
.api
.call(this, entity
, action
, params
, options
);
164 $.widget('civi.crmSnippet', {
170 _originalContent
: null,
172 isOriginalUrl: function() {
176 newUrl
= this._formatUrl(this.options
.url
),
177 oldUrl
= this._formatUrl(this._originalUrl
);
179 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
183 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
184 var arg
= v
.split('=');
185 args
[arg
[0]] = arg
[1];
187 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
188 var arg
= v
.split('=');
189 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
195 resetUrl: function() {
196 this.options
.url
= this._originalUrl
;
198 _create: function() {
199 this.element
.addClass('crm-ajax-container');
200 if (!this.element
.is('.crm-container *')) {
201 this.element
.addClass('crm-container');
203 this._handleOrderLinks();
204 // Set default if not supplied
205 this.options
.url
= this.options
.url
|| document
.location
.href
;
206 this._originalUrl
= this.options
.url
;
208 _onFailure: function(data
, status
) {
209 var msg
, title
= ts('Network Error');
210 if (this.options
.block
) this.element
.unblock();
211 this.element
.trigger('crmAjaxFail', data
);
214 title
= ts('Access Denied');
215 msg
= ts('Ensure you are still logged in and have permission to access this feature.');
218 msg
= ts('Unable to reach the server. Please refresh this page in your browser and try again.');
220 CRM
.alert(msg
, title
, 'error');
222 _onError: function(data
) {
223 this.element
.attr('data-unsaved-changes', 'false').trigger('crmAjaxError', data
);
224 if (this.options
.crmForm
&& this.options
.crmForm
.autoClose
&& this.element
.data('uiDialog')) {
225 this.element
.dialog('close');
228 _formatUrl: function(url
, snippetType
) {
230 url
= url
.split('#')[0];
231 // Add snippet argument to url
233 if (url
.search(/[&?]snippet=/) < 0) {
234 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=' + snippetType
;
236 url
= url
.replace(/snippet=[^&]*/, 'snippet=' + snippetType
);
241 // Hack to deal with civicrm legacy sort functionality
242 _handleOrderLinks: function() {
244 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
245 if (that
.options
.block
) that
.element
.block();
246 $.getJSON(that
._formatUrl(this.href
, 'json')).done(function() {
249 e
.stopImmediatePropagation();
253 refresh: function() {
255 var url
= this._formatUrl(this.options
.url
, 'json');
256 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
257 if (this.options
.block
) this.element
.block();
258 $.getJSON(url
, function(data
) {
259 if (that
.options
.block
) that
.element
.unblock();
260 if (!$.isPlainObject(data
)) {
261 that
._onFailure(data
);
264 if (data
.status
=== 'error') {
269 that
.element
.trigger('crmUnload').trigger('crmBeforeLoad', data
);
270 that
._beforeRemovingContent();
271 that
.element
.html(data
.content
);
272 that
._handleOrderLinks();
273 that
.element
.trigger('crmLoad', data
);
274 if (that
.options
.crmForm
) that
.element
.trigger('crmFormLoad', data
);
275 }).fail(function(data
, msg
, status
) {
276 that
._onFailure(data
, status
);
279 // Perform any cleanup needed before removing/replacing content
280 _beforeRemovingContent: function() {
282 // Save original content to be restored if widget is destroyed
283 if (this._originalContent
=== null) {
284 $('.blockUI', this.element
).remove();
285 this._originalContent
= this.element
.contents().detach();
287 if (window
.tinyMCE
&& tinyMCE
.editors
) {
288 $.each(tinyMCE
.editors
, function(k
) {
289 if ($.contains(that
.element
[0], this.getElement())) {
294 if (this.options
.crmForm
) $('form', this.element
).ajaxFormUnbind();
296 _destroy: function() {
297 this.element
.removeClass('crm-ajax-container').trigger('crmUnload');
298 this._beforeRemovingContent();
299 if (this._originalContent
!== null) {
300 this.element
.empty().append(this._originalContent
);
306 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
308 CRM
.loadPage = function(url
, options
) {
310 target
: '#crm-ajax-dialog-' + (dialogCount
++),
311 dialog
: (options
&& options
.target
) ? false : {}
313 if (options
) $.extend(true, settings
, options
);
316 if (settings
.dialog
) {
317 settings
.dialog
= CRM
.utils
.adjustDialogDefaults(settings
.dialog
);
318 $('<div id="' + settings
.target
.substring(1) + '"></div>')
319 .dialog(settings
.dialog
)
320 .parent().find('.ui-dialog-titlebar')
321 .append($('<a class="crm-dialog-titlebar-print ui-dialog-titlebar-close" title="'+ts('Print window')+'" target="_blank" style="right:3.8em;"/>')
322 .button({icons
: {primary
: 'ui-icon-print'}, text
: false}));
324 // Add handlers to new or existing dialog
325 if ($(settings
.target
).data('uiDialog')) {
327 .on('dialogclose', function() {
328 if (settings
.dialog
&& $(this).attr('data-unsaved-changes') !== 'true') {
329 $(this).crmSnippet('destroy').dialog('destroy').remove();
332 .on('crmLoad', function(e
, data
) {
334 if (e
.target
=== $(settings
.target
)[0] && data
&& !settings
.dialog
.title
&& data
.title
) {
335 $(this).dialog('option', 'title', data
.title
);
338 $(this).parent().find('a.crm-dialog-titlebar-print').attr('href', $(this).data('civiCrmSnippet')._formatUrl($(this).crmSnippet('option', 'url'), '2'));
341 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
342 return $(settings
.target
);
344 CRM
.loadForm = function(url
, options
) {
345 var formErrors
= [], settings
= {
350 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
351 cancelButton
: '.cancel',
352 openInline
: 'a.open-inline, a.button, a.action-item, a.open-inline-noreturn',
353 onCancel: function(event
) {}
356 // Move options that belong to crmForm. Others will be passed through to crmSnippet
357 if (options
) $.each(options
, function(key
, value
) {
358 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
359 settings
.crmForm
[key
] = value
;
362 settings
[key
] = value
;
366 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
368 // CRM-14353 - Warn of unsaved changes for all forms except those which have opted out
369 function cancelAction() {
370 var dirty
= CRM
.utils
.initialValueChanged($('form:not([data-warn-changes=false])', widget
));
371 widget
.attr('data-unsaved-changes', dirty
? 'true' : 'false');
373 var id
= widget
.attr('id') + '-unsaved-alert',
374 title
= widget
.dialog('option', 'title'),
375 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});
376 $('#' + id
).button({icons
: {primary
: 'ui-icon-arrowreturnthick-1-w'}}).click(function(e
) {
377 widget
.attr('data-unsaved-changes', 'false').dialog('open');
383 if (widget
.data('uiDialog')) widget
.on('dialogbeforeclose', function(e
) {
384 // CRM-14353 - Warn unsaved changes if user clicks close button or presses "esc"
385 if (e
.originalEvent
) {
390 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
391 var $el
= $(this).attr('data-unsaved-changes', 'false'),
392 settings
= $el
.crmSnippet('option', 'crmForm');
393 if (settings
.cancelButton
) $(settings
.cancelButton
, this).click(function(e
) {
395 var returnVal
= settings
.onCancel
.call($el
, e
);
396 if (returnVal
!== false) {
397 $el
.trigger('crmFormCancel', e
);
398 if ($el
.data('uiDialog') && settings
.autoClose
) {
402 else if (!settings
.autoClose
) {
403 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
407 if (settings
.validate
) {
408 $("form", this).crmValidate();
410 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
411 url
: data
.url
.replace(/reset=1[&]?/, ''),
413 success: function(response
) {
414 if (response
.content
=== undefined) {
415 $el
.trigger('crmFormSuccess', response
);
416 // Reset form for e.g. "save and new"
417 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
418 // Force reset of original url
419 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
420 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
422 // Close if we are on the original url or the action was "delete" (in which case returning to view may be inappropriate)
423 else if ($el
.data('uiDialog') && (settings
.autoClose
|| response
.action
=== 8)) {
426 else if (settings
.autoClose
=== false) {
427 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
431 if ($el
.crmSnippet('option', 'block')) $el
.unblock();
432 response
.url
= data
.url
;
433 $el
.html(response
.content
).trigger('crmLoad', response
).trigger('crmFormLoad', response
);
434 if (response
.status
=== 'form_error') {
436 $el
.trigger('crmFormError', response
);
437 $.each(response
.errors
|| [], function(formElement
, msg
) {
438 formErrors
.push($('[name="'+formElement
+'"]', $el
).crmError(msg
));
443 beforeSubmit: function(submission
) {
444 $.each(formErrors
, function() {
445 if (this && this.close
) this.close();
447 if ($el
.crmSnippet('option', 'block')) $el
.block();
448 $el
.trigger('crmFormSubmit', submission
);
450 }, settings
.ajaxForm
));
451 if (settings
.openInline
) {
452 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
453 $(this).on('click', settings
.openInline
, function(e
) {
454 if ($(this).is(exclude
+ ', .crm-popup')) {
457 if ($(this).hasClass('open-inline-noreturn')) {
458 // Force reset of original url
459 $el
.data('civiCrmSnippet')._originalUrl
= $(this).attr('href');
461 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
465 if ($el
.data('uiDialog')) {
466 // Show form buttons as part of the dialog
467 var buttonContainers
= '.crm-submit-buttons, .action-link',
470 $(buttonContainers
, $el
).find('input.crm-form-submit, a.button').each(function() {
472 label
= $el
.is('input') ? $el
.attr('value') : $el
.text(),
473 identifier
= $el
.attr('name') || $el
.attr('href');
474 if (!identifier
|| identifier
=== '#' || $.inArray(identifier
, added
) < 0) {
475 var $icon
= $el
.find('.icon'),
476 button
= {'data-identifier': identifier
, text
: label
, click: function() {
480 button
.icons
= {primary
: $icon
.attr('class')};
482 var action
= $el
.attr('crm-icon') || ($el
.hasClass('cancel') ? 'close' : 'check');
483 button
.icons
= {primary
: 'ui-icon-' + action
};
485 buttons
.push(button
);
486 added
.push(identifier
);
488 // display:none causes the form to not submit when pressing "enter"
489 $el
.parents(buttonContainers
).css({height
: 0, padding
: 0, margin
: 0, overflow
: 'hidden'}).find('.crm-button-icon').hide();
491 $el
.dialog('option', 'buttons', buttons
);
493 // Show done button for non-ajax dialogs (e.g. file downloads)
494 $(this).on('submit', "form[data-no-ajax-submit=true]", function() {
495 $el
.dialog('option', 'buttons', [{
497 icons
: {primary
: 'ui-icon-close'},
498 click: function() {$(this).dialog('close');}
502 // Allow a button to prevent ajax submit
503 $('input[data-no-ajax-submit=true]').click(function() {
504 $(this).closest('form').ajaxFormUnbind();
506 // For convenience, focus the first field
507 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
512 * Handler for jQuery click event e.g. $('a').click(CRM.popup);
514 CRM
.popup = function(e
) {
515 var $el
= $(this).first(),
516 url
= $el
.attr('href'),
517 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
518 settings
= $el
.data('popup-settings') || {},
520 settings
.dialog
= settings
.dialog
|| {};
521 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
)) {
524 // Sized based on css class
525 if ($el
.hasClass('small-popup')) {
526 settings
.dialog
.width
= 400;
527 settings
.dialog
.height
= 300;
529 else if ($el
.hasClass('medium-popup')) {
530 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
532 var dialog
= popup(url
, settings
);
533 // Trigger events from the dialog on the original link element
534 $el
.trigger('crmPopupOpen', [dialog
]);
535 // Listen for success events and buffer them so we only trigger once
536 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
539 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
541 $el
.trigger('crmPopupFormSuccess', [dialog
, data
]);
543 $el
.trigger('crmPopupClose', [dialog
, data
]);
548 * An event callback for CRM.popup or a standalone function to refresh the content around a given element
549 * @param e {event|selector}
551 CRM
.refreshParent = function(e
) {
552 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
553 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
554 $table
= $el
.closest('.dataTable');
555 // Call native refresh method on ajax datatables
556 if ($table
.length
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
557 // Refresh ALL datatables - needed for contact relationship tab
558 $.each($.fn
.dataTable
.fnTables(), function() {
559 if ($(this).dataTable().fnSettings().sAjaxSource
) $(this).unblock().dataTable().fnDraw();
562 // Otherwise refresh the nearest crmSnippet
564 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
570 .on('click', 'a.crm-popup', CRM
.popup
)
571 // Close unsaved dialog messages
572 .on('dialogopen', function(e
) {
573 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
575 // Destroy old unsaved dialog
576 .on('dialogcreate', function(e
) {
577 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();
579 // Ensure wysiwyg content is updated prior to ajax submit
580 .on('form-pre-serialize', function(e
) {
581 $('.crm-wysiwyg-enabled', e
.target
).each(function() {
582 CRM
.wysiwyg
.updateElement(this);
585 // Auto-resize dialogs when loading content
586 .on('crmLoad dialogopen', 'div.ui-dialog.ui-resizable.crm-container', function(e
) {
589 $dialog
= $wrapper
.children('.ui-dialog-content');
590 // small delay to allow contents to render
591 window
.setTimeout(function() {
592 var currentHeight
= $wrapper
.outerHeight(),
593 padding
= currentHeight
- $dialog
.height(),
594 newHeight
= $dialog
.prop('scrollHeight') + padding
,
595 menuHeight
= $('#civicrm-menu').outerHeight(),
596 maxHeight
= $(window
).height() - menuHeight
;
597 newHeight
= newHeight
> maxHeight
? maxHeight
: newHeight
;
598 if (newHeight
> (currentHeight
+ 15)) {
599 $dialog
.dialog('option', {
600 position
: {my
: 'center', at
: 'center center+' + (menuHeight
/ 2), of: window
},