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
8 * Almost like {crmURL} but on the client side
9 * eg: var url = CRM.url('civicrm/contact/view', {reset:1,cid:42});
10 * or: $('a.my-link').crmURL();
12 var tplURL
= '/civicrm/example?placeholder';
13 var urlInitted
= false;
14 CRM
.url = function (p
, params
) {
21 console
&& console
.log
&& console
.log('Warning: CRM.url called before initialization');
23 params
= params
|| '';
24 var frag
= p
.split ('?');
25 var url
= tplURL
.replace("civicrm/example", frag
[0]);
27 if (typeof(params
) == 'string') {
28 url
= url
.replace("placeholder", params
);
31 url
= url
.replace("placeholder", $.param(params
));
34 url
+= (url
.indexOf('?') === (url
.length
- 1) ? '' : '&') + frag
[1];
36 // remove trailing "?"
37 if (url
.indexOf('?') === (url
.length
- 1)) {
38 url
= url
.slice(0, (url
.length
- 1));
43 // Backwards compatible with jQuery fn
45 function (p
, params
) {
46 console
&& console
.log
&& console
.log('Calling crmURL from jQuery is deprecated. Please use CRM.url() instead.');
47 return CRM
.url(p
, params
);
51 $.fn
.crmURL = function () {
52 return this.each(function() {
54 this.href
= CRM
.url(this.href
);
62 CRM
.api3 = function(entity
, action
, params
, status
) {
63 if (typeof(entity
) === 'string') {
66 action
: action
.toLowerCase(),
67 json
: JSON
.stringify(params
|| {})
73 json
: JSON
.stringify(entity
)
78 url
: CRM
.url('civicrm/ajax/rest'),
81 type
: params
.action
.indexOf('get') < 0 ? 'POST' : 'GET'
84 // Default status messages
85 if (status
=== true) {
86 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
87 if (params
.action
.indexOf('get') === 0) {
88 status
.start
= ts('Loading...');
89 status
.success
= null;
92 var messages
= status
=== true ? {} : status
;
93 CRM
.status(status
, ajax
);
102 CRM
.api = function(entity
, action
, params
, options
) {
106 success: function(result
, settings
) {
109 error: function(result
, settings
) {
110 $().crmError(result
.error_message
, ts('Error'));
113 callBack: function(result
, settings
) {
114 if (result
.is_error
== 1) {
115 return settings
.error
.call(this, result
, settings
);
117 return settings
.success
.call(this, result
, settings
);
119 ajaxURL
: 'civicrm/ajax/rest'
121 action
= action
.toLowerCase();
122 // Default success handler
128 settings
.success = function() {
129 CRM
.status(ts('Saved'));
134 settings
.success = function() {
135 CRM
.status(ts('Removed'));
142 json
: JSON
.stringify(params
)
144 // Pass copy of settings into closure to preserve its value during multiple requests
147 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
150 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
151 success: function(result
) {
152 stg
.callBack
.call(stg
.context
, result
, stg
);
155 })($.extend({}, settings
, options
));
159 * Backwards compatible with jQuery fn
162 $.fn
.crmAPI = function(entity
, action
, params
, options
) {
163 console
&& console
.log
&& console
.log('Calling crmAPI from jQuery is deprecated. Please use CRM.api() instead.');
164 return CRM
.api
.call(this, entity
, action
, params
, options
);
167 $.widget('civi.crmSnippet', {
173 _originalContent
: null,
175 isOriginalUrl: function() {
179 newUrl
= this._formatUrl(this.options
.url
),
180 oldUrl
= this._formatUrl(this._originalUrl
);
182 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
186 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
187 var arg
= v
.split('=');
188 args
[arg
[0]] = arg
[1];
190 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
191 var arg
= v
.split('=');
192 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
198 resetUrl: function() {
199 this.options
.url
= this._originalUrl
;
201 _create: function() {
202 this.element
.addClass('crm-ajax-container');
203 if (!this.element
.is('.crm-container *')) {
204 this.element
.addClass('crm-container');
206 this._handleOrderLinks();
207 // Set default if not supplied
208 this.options
.url
= this.options
.url
|| document
.location
.href
;
209 this._originalUrl
= this.options
.url
;
211 _onFailure: function(data
) {
212 this.options
.block
&& this.element
.unblock();
213 this.element
.trigger('crmAjaxFail', data
);
214 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
216 _formatUrl: function(url
) {
218 url
= url
.split('#')[0];
219 // Add snippet argument to url
220 if (url
.search(/[&?]snippet=/) < 0) {
221 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
223 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
227 // Hack to deal with civicrm legacy sort functionality
228 _handleOrderLinks: function() {
230 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
231 that
.options
.block
&& that
.element
.block();
232 $.getJSON(that
._formatUrl(this.href
)).done(function() {
235 e
.stopImmediatePropagation();
239 refresh: function() {
241 var url
= this._formatUrl(this.options
.url
);
242 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
243 if (this._originalContent
=== null) {
244 this._originalContent
= this.element
.contents().detach();
246 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
247 $.getJSON(url
, function(data
) {
248 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
249 that
._onFailure(data
);
253 that
.element
.trigger('crmBeforeLoad', data
).html(data
.content
);
254 that
._handleOrderLinks();
255 that
.element
.trigger('crmLoad', data
);
256 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
261 _destroy: function() {
262 this.element
.removeClass('crm-ajax-container');
263 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
264 if (this._originalContent
!== null) {
265 this.element
.empty().append(this._originalContent
);
271 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
273 CRM
.loadPage = function(url
, options
) {
275 target
: '#crm-ajax-dialog-' + (dialogCount
++),
278 if (!options
|| !options
.target
) {
285 options
&& $.extend(true, settings
, options
);
288 if (settings
.dialog
) {
289 // HACK: jQuery UI doesn't support relative height
290 if (typeof settings
.dialog
.height
=== 'string' && settings
.dialog
.height
.indexOf('%') > 0) {
291 settings
.dialog
.height
= parseInt($(window
).height() * (parseFloat(settings
.dialog
.height
)/100), 10);
293 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
294 $(settings
.target
).on('dialogclose', function() {
295 if ($(this).attr('data-unsaved-changes') !== 'true') {
296 $(this).crmSnippet('destroy').dialog('destroy').remove();
300 if (settings
.dialog
&& !settings
.dialog
.title
) {
301 $(settings
.target
).on('crmLoad', function(e
, data
) {
302 if (e
.target
=== $(settings
.target
)[0] && data
&& data
.title
) {
303 $(this).dialog('option', 'title', data
.title
);
307 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
308 return $(settings
.target
);
310 CRM
.loadForm = function(url
, options
) {
316 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
317 cancelButton
: '.cancel',
318 openInline
: 'a.open-inline, a.button, a.action-item',
319 onCancel: function(event
) {},
320 onError: function(data
) {
322 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
).trigger('crmFormError', data
);
323 if (typeof(data
.errors
) == 'object') {
324 $.each(data
.errors
, function(formElement
, msg
) {
325 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
331 // Move options that belong to crmForm. Others will be passed through to crmSnippet
332 options
&& $.each(options
, function(key
, value
) {
333 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
334 settings
.crmForm
[key
] = value
;
337 settings
[key
] = value
;
341 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
343 function cancelAction() {
344 var dirty
= CRM
.utils
.initialValueChanged(widget
),
345 title
= widget
.dialog('option', 'title');
346 widget
.attr('data-unsaved-changes', dirty
? 'true' : 'false').dialog('close');
348 var id
= widget
.attr('id') + '-unsaved-alert',
349 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});
350 $('#' + id
).button({icons
: {primary
: 'ui-icon-arrowreturnthick-1-w'}}).click(function(e
) {
351 widget
.attr('data-unsaved-changes', 'false').dialog('open');
356 if (widget
.data('uiDialog')) {
357 // This is a bit harsh but we are removing jQuery UI's event handler from the close button and adding our own
358 $('.ui-dialog-titlebar-close').first().off().click(cancelAction
);
361 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
363 .attr('data-unsaved-changes', 'false');
364 var settings
= $el
.crmSnippet('option', 'crmForm');
365 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(e
) {
367 var returnVal
= settings
.onCancel
.call($el
, e
);
368 if (returnVal
!== false) {
369 $el
.trigger('crmFormCancel', e
);
370 if ($el
.data('uiDialog') && settings
.autoClose
) {
373 else if (!settings
.autoClose
) {
374 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
378 if (settings
.validate
) {
379 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
381 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
382 url
: data
.url
.replace(/reset=1[&]?/, ''),
384 success: function(response
) {
385 if (response
.status
!== 'form_error') {
386 $el
.crmSnippet('option', 'block') && $el
.unblock();
387 $el
.trigger('crmFormSuccess', response
);
388 // Reset form for e.g. "save and new"
389 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
390 // Force reset of original url
391 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
392 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
394 else if ($el
.data('uiDialog') && settings
.autoClose
) {
397 else if (settings
.autoClose
=== false) {
398 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
402 response
.url
= data
.url
;
403 settings
.onError
.call($el
, response
);
406 beforeSerialize: function(form
, options
) {
407 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
408 $.each(CKEDITOR
.instances
, function() {
409 this.updateElement
&& this.updateElement();
413 beforeSubmit: function(submission
) {
414 $el
.crmSnippet('option', 'block') && $el
.block();
415 $el
.trigger('crmFormSubmit', submission
);
417 }, settings
.ajaxForm
));
418 if (settings
.openInline
) {
419 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
420 $(settings
.openInline
, this).not(exclude
+ ', .crm-popup').click(function(event
) {
421 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
425 // For convenience, focus the first field
426 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
431 * Handler for jQuery click event e.g. $('a').click(CRM.popup)
434 CRM
.popup = function(e
) {
435 var $el
= $(this).first(),
436 url
= $el
.attr('href'),
437 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
438 settings
= $el
.data('popup-settings') || {},
440 settings
.dialog
= settings
.dialog
|| {};
441 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
)) {
444 // Sized based on css class
445 if ($el
.hasClass('small-popup')) {
446 settings
.dialog
.width
= 400;
447 settings
.dialog
.height
= 300;
449 else if ($el
.hasClass('medium-popup')) {
450 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
452 else if ($el
.hasClass('huge-popup')) {
453 settings
.dialog
.height
= '90%';
455 var dialog
= popup(url
, settings
);
456 // Trigger events from the dialog on the original link element
457 $el
.trigger('crmPopupOpen', [dialog
]);
458 // Listen for success events and buffer them so we only trigger once
459 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
462 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
464 $el
.trigger('crmPopupFormSuccess', [dialog
, data
]);
466 $el
.trigger('crmPopupClose', [dialog
, data
]);
471 * An event callback for CRM.popup or a standalone function to refresh the content around a popup link
472 * @param e event|selector
474 CRM
.refreshParent = function(e
) {
475 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
476 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
477 $table
= $el
.closest('.dataTable');
478 // Call native refresh method on ajax datatables
479 if ($table
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
480 // Refresh ALL datatables - needed for contact relationship tab
481 $.each($.fn
.dataTable
.fnTables(), function() {
482 $(this).dataTable().fnSettings().sAjaxSource
&& $(this).unblock().dataTable().fnDraw();
485 // Otherwise refresh the nearest crmSnippet
487 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
493 .on('click', 'a.crm-popup', CRM
.popup
)
494 // Close unsaved dialog messages
495 .on('dialogopen', function(e
) {
496 $('.alert.unsaved-dialog .ui-notify-cross', '#crm-notification-container').click();
498 // Destroy old unsaved dialog
499 .on('dialogcreate', function(e
) {
500 $('.ui-dialog-content.crm-ajax-container:hidden[data-unsaved-changes=true]').crmSnippet('destroy').dialog('destroy').remove();