Merge pull request #2808 from colemanw/popups
[civicrm-core.git] / js / crm.ajax.js
1 // https://civicrm.org/licensing
2 /**
3 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/AJAX+Interface
4 * @see https://wiki.civicrm.org/confluence/display/CRMDOC/Ajax+Pages+and+Forms
5 */
6 (function($, CRM) {
7 /**
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();
11 */
12 var tplURL = '/civicrm/example?placeholder';
13 var urlInitted = false;
14 CRM.url = function (p, params) {
15 if (p == "init") {
16 tplURL = params;
17 urlInitted = true;
18 return;
19 }
20 if (!urlInitted) {
21 console && console.log && console.log('Warning: CRM.url called before initialization');
22 }
23 params = params || '';
24 var frag = p.split ('?');
25 var url = tplURL.replace("civicrm/example", frag[0]);
26
27 if (typeof(params) == 'string') {
28 url = url.replace("placeholder", params);
29 }
30 else {
31 url = url.replace("placeholder", $.param(params));
32 }
33 if (frag[1]) {
34 url += (url.indexOf('?') === (url.length - 1) ? '' : '&') + frag[1];
35 }
36 // remove trailing "?"
37 if (url.indexOf('?') === (url.length - 1)) {
38 url = url.slice(0, (url.length - 1));
39 }
40 return url;
41 };
42
43 // Backwards compatible with jQuery fn
44 $.extend ({'crmURL':
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);
48 }
49 });
50
51 $.fn.crmURL = function () {
52 return this.each(function() {
53 if (this.href) {
54 this.href = CRM.url(this.href);
55 }
56 });
57 };
58
59 /**
60 * AJAX api
61 */
62 CRM.api3 = function(entity, action, params, status) {
63 if (typeof(entity) === 'string') {
64 params = {
65 entity: entity,
66 action: action.toLowerCase(),
67 json: JSON.stringify(params || {})
68 };
69 } else {
70 params = {
71 entity: 'api3',
72 action: 'call',
73 json: JSON.stringify(entity)
74 }
75 }
76 var ajax = $.ajax({
77 url: CRM.url('civicrm/ajax/rest'),
78 dataType: 'json',
79 data: params,
80 type: params.action.indexOf('get') < 0 ? 'POST' : 'GET'
81 });
82 if (status) {
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;
89 }
90 }
91 var messages = status === true ? {} : status;
92 CRM.status(status, ajax);
93 }
94 return ajax;
95 };
96
97 /**
98 * @deprecated
99 * AJAX api
100 */
101 CRM.api = function(entity, action, params, options) {
102 // Default settings
103 var settings = {
104 context: null,
105 success: function(result, settings) {
106 return true;
107 },
108 error: function(result, settings) {
109 $().crmError(result.error_message, ts('Error'));
110 return false;
111 },
112 callBack: function(result, settings) {
113 if (result.is_error == 1) {
114 return settings.error.call(this, result, settings);
115 }
116 return settings.success.call(this, result, settings);
117 },
118 ajaxURL: 'civicrm/ajax/rest'
119 };
120 action = action.toLowerCase();
121 // Default success handler
122 switch (action) {
123 case "update":
124 case "create":
125 case "setvalue":
126 case "replace":
127 settings.success = function() {
128 CRM.status(ts('Saved'));
129 return true;
130 };
131 break;
132 case "delete":
133 settings.success = function() {
134 CRM.status(ts('Removed'));
135 return true;
136 };
137 }
138 params = {
139 entity: entity,
140 action: action,
141 json: JSON.stringify(params)
142 };
143 // Pass copy of settings into closure to preserve its value during multiple requests
144 (function(stg) {
145 $.ajax({
146 url: stg.ajaxURL.indexOf('http') === 0 ? stg.ajaxURL : CRM.url(stg.ajaxURL),
147 dataType: 'json',
148 data: params,
149 type: action.indexOf('get') < 0 ? 'POST' : 'GET',
150 success: function(result) {
151 stg.callBack.call(stg.context, result, stg);
152 }
153 });
154 })($.extend({}, settings, options));
155 };
156
157 /**
158 * Backwards compatible with jQuery fn
159 * @deprecated
160 */
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);
164 };
165
166 $.widget('civi.crmSnippet', {
167 options: {
168 url: null,
169 block: true,
170 crmForm: null
171 },
172 _originalContent: null,
173 _originalUrl: null,
174 isOriginalUrl: function() {
175 var
176 args = {},
177 same = true,
178 newUrl = this._formatUrl(this.options.url),
179 oldUrl = this._formatUrl(this._originalUrl);
180 // Compare path
181 if (newUrl.split('?')[0] !== oldUrl.split('?')[0]) {
182 return false;
183 }
184 // Compare arguments
185 $.each(newUrl.split('?')[1].split('&'), function(k, v) {
186 var arg = v.split('=');
187 args[arg[0]] = arg[1];
188 });
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]]) {
192 same = false;
193 }
194 });
195 return same;
196 },
197 resetUrl: function() {
198 this.options.url = this._originalUrl;
199 },
200 _create: function() {
201 this.element.addClass('crm-ajax-container');
202 if (!this.element.is('.crm-container *')) {
203 this.element.addClass('crm-container');
204 }
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;
209 },
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');
214 },
215 _formatUrl: function(url) {
216 // Strip hash
217 url = url.split('#')[0];
218 // Add snippet argument to url
219 if (url.search(/[&?]snippet=/) < 0) {
220 url += (url.indexOf('?') < 0 ? '?' : '&') + 'snippet=json';
221 } else {
222 url = url.replace(/snippet=[^&]*/, 'snippet=json');
223 }
224 return url;
225 },
226 // Hack to deal with civicrm legacy sort functionality
227 _handleOrderLinks: function() {
228 var that = this;
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() {
232 that.refresh();
233 });
234 e.stopImmediatePropagation();
235 return false;
236 });
237 },
238 refresh: function() {
239 var that = this;
240 var url = this._formatUrl(this.options.url);
241 this.options.crmForm && $('form', this.element).ajaxFormUnbind();
242 this.options.block && $('.blockOverlay', this.element).length < 1 && this.element.block();
243 $.getJSON(url, function(data) {
244 if (typeof(data) != 'object' || typeof(data.content) != 'string') {
245 that._onFailure(data);
246 return;
247 }
248 data.url = url;
249 that.element.trigger('crmBeforeLoad', data);
250 if (that._originalContent === null) {
251 that._originalContent = that.element.contents().detach();
252 }
253 that.element.html(data.content);
254 that._handleOrderLinks();
255 that.element.trigger('crmLoad', data);
256 that.options.crmForm && that.element.trigger('crmFormLoad', data);
257 }).fail(function() {
258 that._onFailure();
259 });
260 },
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);
266 }
267 }
268 });
269
270 var dialogCount = 0,
271 exclude = '[href^=#], [href^=javascript], [onclick], .no-popup, .cancel';
272
273 CRM.loadPage = function(url, options) {
274 var settings = {
275 target: '#crm-ajax-dialog-' + (dialogCount++),
276 dialog: false
277 };
278 if (!options || !options.target) {
279 settings.dialog = {
280 modal: true,
281 width: '65%',
282 height: '75%'
283 };
284 }
285 options && $.extend(true, settings, options);
286 settings.url = url;
287 // Create new dialog
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);
292 }
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 $(this).crmSnippet('destroy').dialog('destroy').remove();
296 });
297 }
298 if (settings.dialog && !settings.dialog.title) {
299 $(settings.target).on('crmLoad', function(e, data) {
300 if (e.target === $(settings.target)[0] && data && data.title) {
301 $(this).dialog('option', 'title', data.title);
302 }
303 });
304 }
305 $(settings.target).crmSnippet(settings).crmSnippet('refresh');
306 return $(settings.target);
307 };
308 CRM.loadForm = function(url, options) {
309 var settings = {
310 crmForm: {
311 ajaxForm: {},
312 autoClose: true,
313 validate: true,
314 refreshAction: ['next_new', 'submit_savenext', 'upload_new'],
315 cancelButton: '.cancel',
316 openInline: 'a.open-inline, a.button, a.action-item',
317 onCancel: function(event) {},
318 onError: function(data) {
319 var $el = $(this);
320 $el.html(data.content).trigger('crmLoad', data).trigger('crmFormLoad', data).trigger('crmFormError', data);
321 if (typeof(data.errors) == 'object') {
322 $.each(data.errors, function(formElement, msg) {
323 $('[name="'+formElement+'"]', $el).crmError(msg);
324 });
325 }
326 }
327 }
328 };
329 // Move options that belong to crmForm. Others will be passed through to crmSnippet
330 options && $.each(options, function(key, value) {
331 if (typeof(settings.crmForm[key]) !== 'undefined') {
332 settings.crmForm[key] = value;
333 }
334 else {
335 settings[key] = value;
336 }
337 });
338
339 var widget = CRM.loadPage(url, settings).off('.crmForm');
340
341 widget.on('crmFormLoad.crmForm', function(event, data) {
342 var $el = $(this);
343 var settings = $el.crmSnippet('option', 'crmForm');
344 settings.cancelButton && $(settings.cancelButton, this).click(function(event) {
345 var returnVal = settings.onCancel.call($el, event);
346 if (returnVal !== false) {
347 $el.trigger('crmFormCancel', event);
348 if ($el.data('uiDialog') && settings.autoClose) {
349 $el.dialog('close');
350 }
351 else if (!settings.autoClose) {
352 $el.crmSnippet('resetUrl').crmSnippet('refresh');
353 }
354 }
355 return returnVal === false;
356 });
357 if (settings.validate) {
358 $("form", this).validate(typeof(settings.validate) == 'object' ? settings.validate : CRM.validate.params);
359 }
360 $("form:not('[data-no-ajax-submit=true]')", this).ajaxForm($.extend({
361 url: data.url.replace(/reset=1[&]?/, ''),
362 dataType: 'json',
363 success: function(response) {
364 if (response.status !== 'form_error') {
365 $el.crmSnippet('option', 'block') && $el.unblock();
366 $el.trigger('crmFormSuccess', response);
367 // Reset form for e.g. "save and new"
368 if (response.userContext && settings.refreshAction && $.inArray(response.buttonName, settings.refreshAction) >= 0) {
369 // Force reset of original url
370 $el.data('civiCrmSnippet')._originalUrl = response.userContext;
371 $el.crmSnippet('resetUrl').crmSnippet('refresh');
372 }
373 else if ($el.data('uiDialog') && settings.autoClose) {
374 $el.dialog('close');
375 }
376 else if (settings.autoClose === false) {
377 $el.crmSnippet('resetUrl').crmSnippet('refresh');
378 }
379 }
380 else {
381 response.url = data.url;
382 settings.onError.call($el, response);
383 }
384 },
385 beforeSerialize: function(form, options) {
386 if (window.CKEDITOR && window.CKEDITOR.instances) {
387 $.each(CKEDITOR.instances, function() {
388 this.updateElement && this.updateElement();
389 });
390 }
391 },
392 beforeSubmit: function(submission) {
393 $el.crmSnippet('option', 'block') && $el.block();
394 $el.trigger('crmFormSubmit', submission);
395 }
396 }, settings.ajaxForm));
397 if (settings.openInline) {
398 settings.autoClose = $el.crmSnippet('isOriginalUrl');
399 $(settings.openInline, this).not(exclude + ', .crm-popup').click(function(event) {
400 $el.crmSnippet('option', 'url', $(this).attr('href')).crmSnippet('refresh');
401 return false;
402 });
403 }
404 // For convenience, focus the first field
405 $('input[type=text], textarea, select', this).filter(':visible').first().not('.dateplugin').focus();
406 });
407 return widget;
408 };
409 /**
410 * Handler for jQuery click event e.g. $('a').click(CRM.popup)
411 * @returns {boolean}
412 */
413 CRM.popup = function(e) {
414 var $el = $(this).first(),
415 url = $el.attr('href'),
416 popup = $el.data('popup-type') === 'page' ? CRM.loadPage : CRM.loadForm,
417 settings = $el.data('popup-settings') || {},
418 formSuccess = false;
419 settings.dialog = settings.dialog || {};
420 if (e.isDefaultPrevented() || !CRM.config.ajaxPopupsEnabled || !url || $el.is(exclude)) {
421 return;
422 }
423 // Sized based on css class
424 if ($el.hasClass('small-popup')) {
425 settings.dialog.width = 400;
426 settings.dialog.height = 300;
427 }
428 else if ($el.hasClass('medium-popup')) {
429 settings.dialog.width = settings.dialog.height = '50%';
430 }
431 else if ($el.hasClass('huge-popup')) {
432 settings.dialog.height = '90%';
433 }
434 var dialog = popup(url, settings);
435 // Trigger events from the dialog on the original link element
436 $el.trigger('crmPopupOpen', [dialog]);
437 // Buffer this event so it only fires once
438 dialog.on('crmFormSuccess.crmPopup', function(e, data) {
439 formSuccess = true;
440 });
441 dialog.on('dialogclose.crmPopup', function(e, data) {
442 if (formSuccess) {
443 $el.trigger('crmPopupFormSuccess', [dialog, data]);
444 }
445 $el.trigger('crmPopupClose', [dialog, data]);
446 });
447 e.preventDefault();
448 };
449 /**
450 * An event callback for CRM.popup or a standalone function to refresh the content around a popup link
451 * @param e event|selector
452 */
453 CRM.refreshParent = function(e) {
454 // Use e.target if input smells like an event, otherwise assume it's a jQuery selector
455 var $el = (e.stopPropagation && e.target) ? $(e.target) : $(e),
456 $table = $el.closest('.dataTable');
457 // Call native refresh method on ajax datatables
458 if ($table && $.fn.DataTable.fnIsDataTable($table[0]) && $table.dataTable().fnSettings().sAjaxSource) {
459 // Refresh ALL datatables - needed for contact relationship tab
460 $.each($.fn.dataTable.fnTables(), function() {
461 $(this).dataTable().fnSettings().sAjaxSource && $(this).unblock().dataTable().fnDraw();
462 });
463 }
464 // Otherwise refresh the nearest crmSnippet
465 else {
466 $el.closest('.crm-ajax-container, #crm-main-content-wrapper').crmSnippet().crmSnippet('refresh');
467 }
468 };
469
470 $(function($) {
471 $('body').on('click', 'a.crm-popup', CRM.popup);
472 });
473
474 }(jQuery, CRM));