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
)
77 url
: CRM
.url('civicrm/ajax/rest'),
80 type
: params
.action
.indexOf('get') < 0 ? 'POST' : 'GET'
83 // Default status messages
84 if (status
=== true) {
85 status
= {success
: params
.action
=== 'delete' ? ts('Removed') : ts('Saved')};
86 if (params
.action
.indexOf('get') === 0) {
87 status
.start
= ts('Loading...');
88 status
.success
= null;
91 var messages
= status
=== true ? {} : status
;
92 CRM
.status(status
, ajax
);
101 CRM
.api = function(entity
, action
, params
, options
) {
105 success: function(result
, settings
) {
108 error: function(result
, settings
) {
109 $().crmError(result
.error_message
, ts('Error'));
112 callBack: function(result
, settings
) {
113 if (result
.is_error
== 1) {
114 return settings
.error
.call(this, result
, settings
);
116 return settings
.success
.call(this, result
, settings
);
118 ajaxURL
: 'civicrm/ajax/rest'
120 action
= action
.toLowerCase();
121 // Default success handler
127 settings
.success = function() {
128 CRM
.status(ts('Saved'));
133 settings
.success = function() {
134 CRM
.status(ts('Removed'));
141 json
: JSON
.stringify(params
)
143 // Pass copy of settings into closure to preserve its value during multiple requests
146 url
: stg
.ajaxURL
.indexOf('http') === 0 ? stg
.ajaxURL
: CRM
.url(stg
.ajaxURL
),
149 type
: action
.indexOf('get') < 0 ? 'POST' : 'GET',
150 success: function(result
) {
151 stg
.callBack
.call(stg
.context
, result
, stg
);
154 })($.extend({}, settings
, options
));
158 * Backwards compatible with jQuery fn
161 $.fn
.crmAPI = function(entity
, action
, params
, options
) {
162 console
&& console
.log
&& console
.log('Calling crmAPI from jQuery is deprecated. Please use CRM.api() instead.');
163 return CRM
.api
.call(this, entity
, action
, params
, options
);
166 $.widget('civi.crmSnippet', {
172 _originalContent
: null,
174 isOriginalUrl: function() {
178 newUrl
= this._formatUrl(this.options
.url
),
179 oldUrl
= this._formatUrl(this._originalUrl
);
181 if (newUrl
.split('?')[0] !== oldUrl
.split('?')[0]) {
185 $.each(newUrl
.split('?')[1].split('&'), function(k
, v
) {
186 var arg
= v
.split('=');
187 args
[arg
[0]] = arg
[1];
189 $.each(oldUrl
.split('?')[1].split('&'), function(k
, v
) {
190 var arg
= v
.split('=');
191 if (args
[arg
[0]] !== undefined && arg
[1] !== args
[arg
[0]]) {
197 resetUrl: function() {
198 this.options
.url
= this._originalUrl
;
200 _create: function() {
201 this.element
.addClass('crm-ajax-container');
202 if (!this.element
.is('.crm-container *')) {
203 this.element
.addClass('crm-container');
205 this._handleOrderLinks();
206 // Set default if not supplied
207 this.options
.url
= this.options
.url
|| document
.location
.href
;
208 this._originalUrl
= this.options
.url
;
210 _onFailure: function(data
) {
211 this.options
.block
&& this.element
.unblock();
212 this.element
.trigger('crmAjaxFail', data
);
213 CRM
.alert(ts('Unable to reach the server. Please refresh this page in your browser and try again.'), ts('Network Error'), 'error');
215 _formatUrl: function(url
) {
217 url
= url
.split('#')[0];
218 // Add snippet argument to url
219 if (url
.search(/[&?]snippet=/) < 0) {
220 url
+= (url
.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
222 url
= url
.replace(/snippet=[^&]*/, 'snippet=json');
226 // Hack to deal with civicrm legacy sort functionality
227 _handleOrderLinks: function() {
229 $('a.crm-weight-arrow', that
.element
).click(function(e
) {
230 that
.options
.block
&& that
.element
.block();
231 $.getJSON(that
._formatUrl(this.href
)).done(function() {
234 e
.stopImmediatePropagation();
238 refresh: function() {
240 var url
= this._formatUrl(this.options
.url
);
241 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
242 if (this._originalContent
=== null) {
243 this._originalContent
= this.element
.contents().detach();
245 this.options
.block
&& $('.blockOverlay', this.element
).length
< 1 && this.element
.block();
246 $.getJSON(url
, function(data
) {
247 if (typeof(data
) != 'object' || typeof(data
.content
) != 'string') {
248 that
._onFailure(data
);
252 that
.element
.trigger('crmBeforeLoad', data
).html(data
.content
);
253 that
._handleOrderLinks();
254 that
.element
.trigger('crmLoad', data
);
255 that
.options
.crmForm
&& that
.element
.trigger('crmFormLoad', data
);
260 _destroy: function() {
261 this.element
.removeClass('crm-ajax-container');
262 this.options
.crmForm
&& $('form', this.element
).ajaxFormUnbind();
263 if (this._originalContent
!== null) {
264 this.element
.empty().append(this._originalContent
);
270 exclude
= '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
272 CRM
.loadPage = function(url
, options
) {
274 target
: '#crm-ajax-dialog-' + (dialogCount
++),
277 if (!options
|| !options
.target
) {
284 options
&& $.extend(true, settings
, options
);
287 if (settings
.dialog
) {
288 // HACK: jQuery UI doesn't support relative height
289 if (typeof settings
.dialog
.height
=== 'string' && settings
.dialog
.height
.indexOf('%') > 0) {
290 settings
.dialog
.height
= parseInt($(window
).height() * (parseFloat(settings
.dialog
.height
)/100), 10);
292 $('<div id="'+ settings
.target
.substring(1) +'"><div class="crm-loading-element">' + ts('Loading') + '...</div></div>').dialog(settings
.dialog
);
293 $(settings
.target
).on('dialogclose', function() {
294 $(this).crmSnippet('destroy').dialog('destroy').remove();
297 if (settings
.dialog
&& !settings
.dialog
.title
) {
298 $(settings
.target
).on('crmLoad', function(e
, data
) {
299 if (e
.target
=== $(settings
.target
)[0] && data
&& data
.title
) {
300 $(this).dialog('option', 'title', data
.title
);
304 $(settings
.target
).crmSnippet(settings
).crmSnippet('refresh');
305 return $(settings
.target
);
307 CRM
.loadForm = function(url
, options
) {
313 refreshAction
: ['next_new', 'submit_savenext', 'upload_new'],
314 cancelButton
: '.cancel',
315 openInline
: 'a.open-inline, a.button, a.action-item',
316 onCancel: function(event
) {},
317 onError: function(data
) {
319 $el
.html(data
.content
).trigger('crmLoad', data
).trigger('crmFormLoad', data
).trigger('crmFormError', data
);
320 if (typeof(data
.errors
) == 'object') {
321 $.each(data
.errors
, function(formElement
, msg
) {
322 $('[name="'+formElement
+'"]', $el
).crmError(msg
);
328 // Move options that belong to crmForm. Others will be passed through to crmSnippet
329 options
&& $.each(options
, function(key
, value
) {
330 if (typeof(settings
.crmForm
[key
]) !== 'undefined') {
331 settings
.crmForm
[key
] = value
;
334 settings
[key
] = value
;
338 var widget
= CRM
.loadPage(url
, settings
).off('.crmForm');
340 widget
.on('crmFormLoad.crmForm', function(event
, data
) {
342 var settings
= $el
.crmSnippet('option', 'crmForm');
343 settings
.cancelButton
&& $(settings
.cancelButton
, this).click(function(event
) {
344 var returnVal
= settings
.onCancel
.call($el
, event
);
345 if (returnVal
!== false) {
346 $el
.trigger('crmFormCancel', event
);
347 if ($el
.data('uiDialog') && settings
.autoClose
) {
350 else if (!settings
.autoClose
) {
351 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
354 return returnVal
=== false;
356 if (settings
.validate
) {
357 $("form", this).validate(typeof(settings
.validate
) == 'object' ? settings
.validate
: CRM
.validate
.params
);
359 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
360 url
: data
.url
.replace(/reset=1[&]?/, ''),
362 success: function(response
) {
363 if (response
.status
!== 'form_error') {
364 $el
.crmSnippet('option', 'block') && $el
.unblock();
365 $el
.trigger('crmFormSuccess', response
);
366 // Reset form for e.g. "save and new"
367 if (response
.userContext
&& (response
.status
=== 'redirect' || (settings
.refreshAction
&& $.inArray(response
.buttonName
, settings
.refreshAction
) >= 0))) {
368 // Force reset of original url
369 $el
.data('civiCrmSnippet')._originalUrl
= response
.userContext
;
370 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
372 else if ($el
.data('uiDialog') && settings
.autoClose
) {
375 else if (settings
.autoClose
=== false) {
376 $el
.crmSnippet('resetUrl').crmSnippet('refresh');
380 response
.url
= data
.url
;
381 settings
.onError
.call($el
, response
);
384 beforeSerialize: function(form
, options
) {
385 if (window
.CKEDITOR
&& window
.CKEDITOR
.instances
) {
386 $.each(CKEDITOR
.instances
, function() {
387 this.updateElement
&& this.updateElement();
391 beforeSubmit: function(submission
) {
392 $el
.crmSnippet('option', 'block') && $el
.block();
393 $el
.trigger('crmFormSubmit', submission
);
395 }, settings
.ajaxForm
));
396 if (settings
.openInline
) {
397 settings
.autoClose
= $el
.crmSnippet('isOriginalUrl');
398 $(settings
.openInline
, this).not(exclude
+ ', .crm-popup').click(function(event
) {
399 $el
.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
403 // For convenience, focus the first field
404 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
409 * Handler for jQuery click event e.g. $('a').click(CRM.popup)
412 CRM
.popup = function(e
) {
413 var $el
= $(this).first(),
414 url
= $el
.attr('href'),
415 popup
= $el
.data('popup-type') === 'page' ? CRM
.loadPage
: CRM
.loadForm
,
416 settings
= $el
.data('popup-settings') || {},
418 settings
.dialog
= settings
.dialog
|| {};
419 if (e
.isDefaultPrevented() || !CRM
.config
.ajaxPopupsEnabled
|| !url
|| $el
.is(exclude
)) {
422 // Sized based on css class
423 if ($el
.hasClass('small-popup')) {
424 settings
.dialog
.width
= 400;
425 settings
.dialog
.height
= 300;
427 else if ($el
.hasClass('medium-popup')) {
428 settings
.dialog
.width
= settings
.dialog
.height
= '50%';
430 else if ($el
.hasClass('huge-popup')) {
431 settings
.dialog
.height
= '90%';
433 var dialog
= popup(url
, settings
);
434 // Trigger events from the dialog on the original link element
435 $el
.trigger('crmPopupOpen', [dialog
]);
436 // Listen for success events and buffer them so we only trigger once
437 dialog
.on('crmFormSuccess.crmPopup crmPopupFormSuccess.crmPopup', function() {
440 dialog
.on('dialogclose.crmPopup', function(e
, data
) {
442 $el
.trigger('crmPopupFormSuccess', [dialog
, data
]);
444 $el
.trigger('crmPopupClose', [dialog
, data
]);
449 * An event callback for CRM.popup or a standalone function to refresh the content around a popup link
450 * @param e event|selector
452 CRM
.refreshParent = function(e
) {
453 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
454 var $el
= (e
.stopPropagation
&& e
.target
) ? $(e
.target
) : $(e
),
455 $table
= $el
.closest('.dataTable');
456 // Call native refresh method on ajax datatables
457 if ($table
&& $.fn
.DataTable
.fnIsDataTable($table
[0]) && $table
.dataTable().fnSettings().sAjaxSource
) {
458 // Refresh ALL datatables - needed for contact relationship tab
459 $.each($.fn
.dataTable
.fnTables(), function() {
460 $(this).dataTable().fnSettings().sAjaxSource
&& $(this).unblock().dataTable().fnDraw();
463 // Otherwise refresh the nearest crmSnippet
465 $el
.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
470 $('body').on('click', 'a.crm-popup', CRM
.popup
);