Passed
Push — master ( bdadbe...4fc601 )
by Jean-Christophe
01:54
created

JsUtilsAjaxTrait::postFormOnClick()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 5
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
namespace Ajax\common\traits;
3
4
use Ajax\service\AjaxTransition;
5
use Ajax\service\Javascript;
6
use Ajax\service\JString;
7
use Ubiquity\utils\base\UString;
0 ignored issues
show
Bug introduced by
The type Ubiquity\utils\base\UString was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
8
9
/**
10
 *
11
 * @author jc
12
 * @property array $jquery_code_for_compile
13
 * @property array $params
14
 */
15
trait JsUtilsAjaxTrait {
16
17
	protected $ajaxTransition;
18
19
	protected $ajaxLoader = "<div class=\"ui active centered inline text loader\">Loading</div>";
20
21
	abstract public function getUrl($url);
22
23
	abstract public function _add_event($element, $js, $event, $preventDefault = false, $stopPropagation = false, $immediatly = true);
24
25
	abstract public function interval($jsCode, $time, $globalName = null, $immediatly = true);
26
27
	protected function _ajax($method, $url, $responseElement = "", $parameters = []) {
28
		if (isset($this->params["ajax"])) {
29
			extract($this->params["ajax"]);
30
		}
31
		extract($parameters);
32
33
		$jsCallback = isset($jsCallback) ? $jsCallback : "";
34
		$retour = $this->_getAjaxUrl($url, $attr);
35
		$originalSelector = $responseElement;
36
		$responseElement = $this->_getResponseElement($responseElement);
37
		$retour .= "var self=this;\n";
38
		$before = isset($before) ? $before : "";
39
		$retour .= $before;
40
		if ($hasLoader === true && JString::isNotNull($responseElement)) {
41
			$this->addLoading($retour, $responseElement, $ajaxLoader);
42
		} elseif ($hasLoader === "internal") {
43
			$retour .= "\n$(this).addClass('loading');";
44
		}
45
		$ajaxParameters = [
46
			"url" => "url",
47
			"method" => "'" . \strtoupper($method) . "'"
48
		];
49
50
		$ajaxParameters["async"] = ($async ? "true" : "false");
51
52
		if (isset($params)) {
53
			$ajaxParameters["data"] = self::_correctParams($params, $parameters);
54
		}
55
		if (isset($headers)) {
56
			$ajaxParameters["headers"] = $headers;
57
		}
58
		$this->createAjaxParameters($ajaxParameters, $parameters);
59
		$retour .= "$.ajax({" . $this->implodeAjaxParameters($ajaxParameters) . "}).done(function( data, textStatus, jqXHR ) {\n";
60
		$retour .= $this->_getOnAjaxDone($responseElement, $jqueryDone, $ajaxTransition, $jsCallback, $hasLoader, ($historize ? $originalSelector : null)) . "});\n";
61
		$retour = $this->_addJsCondition($jsCondition, $retour);
62
		if ($immediatly)
63
			$this->jquery_code_for_compile[] = $retour;
64
		return $retour;
65
	}
66
67
	protected function createAjaxParameters(&$original, $parameters) {
68
		$validParameters = [
69
			"contentType" => "%value%",
70
			"dataType" => "'%value%'",
71
			"beforeSend" => "function(jqXHR,settings){%value%}",
72
			"complete" => "function(jqXHR){%value%}"
73
		];
74
		foreach ($validParameters as $param => $mask) {
75
			if (isset($parameters[$param])) {
76
				$original[$param] = \str_replace("%value%", $parameters[$param], $mask);
77
			}
78
		}
79
	}
80
81
	protected function implodeAjaxParameters($ajaxParameters) {
82
		$s = '';
83
		foreach ($ajaxParameters as $k => $v) {
84
			if ($s !== '') {
85
				$s .= ',';
86
			}
87
			if (is_array($v)) {
88
				$s .= "'{$k}':{" . self::implodeAjaxParameters($v) . "}";
0 ignored issues
show
Bug Best Practice introduced by
The method Ajax\common\traits\JsUti...implodeAjaxParameters() is not static, but was called statically. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-call  annotation

88
				$s .= "'{$k}':{" . self::/** @scrutinizer ignore-call */ implodeAjaxParameters($v) . "}";
Loading history...
89
			} else {
90
				$s .= "'{$k}':{$v}";
91
			}
92
		}
93
		return $s;
94
	}
95
96
	protected function _addJsCondition($jsCondition, $jsSource) {
97
		if (isset($jsCondition)) {
98
			return "if(" . $jsCondition . "){\n" . $jsSource . "\n}";
99
		}
100
		return $jsSource;
101
	}
102
103
	protected function _getAjaxUrl($url, $attr) {
104
		$url = $this->_correctAjaxUrl($url);
105
		$retour = "url='" . $url . "';";
106
		$slash = "/";
107
		if (JString::endswith($url, "/") === true) {
108
			$slash = "";
109
		}
110
		if (JString::isNotNull($attr)) {
111
			if ($attr === "value") {
112
				$retour .= "url=url+'" . $slash . "'+$(this).val();\n";
113
			} elseif ($attr === "html") {
114
				$retour .= "url=url+'" . $slash . "'+$(this).html();\n";
115
			} elseif (\substr($attr, 0, 3) === "js:") {
116
				$retour .= "url=url+'" . $slash . "'+" . \substr($attr, 3) . ";\n";
117
			} elseif ($attr !== null && $attr !== "")
118
				$retour .= "url=url+'" . $slash . "'+($(this).attr('" . $attr . "')||'');\n";
119
		}
120
		return $retour;
121
	}
122
123
	protected function onPopstate() {
124
		return "window.onpopstate = function(e){if(e.state){var target=e.state.jqueryDone;$(e.state.selector)[target](e.state.html);}};";
125
	}
126
127
	protected function autoActiveLinks($previousURL = "window.location.href") {
128
		$result = "\nfunction getHref(url) { return \$('a').filter(function(){return \$(this).prop('href') == url; });}";
129
		$result .= "\nvar myurl={$previousURL};if(window._previousURL) getHref(window._previousURL).removeClass('active');getHref(myurl).addClass('active');window._previousURL=myurl;";
130
		return $result;
131
	}
132
133
	protected function _getOnAjaxDone($responseElement, $jqueryDone, $ajaxTransition, $jsCallback, $hasLoader = false, $history = null) {
134
		$retour = "";
135
		$call = null;
136
		if (JString::isNotNull($responseElement)) {
137
			if (isset($ajaxTransition)) {
138
				$call = $this->setAjaxDataCall($ajaxTransition);
139
			} elseif (isset($this->ajaxTransition)) {
140
				$call = $this->ajaxTransition;
141
			}
142
			if (\is_callable($call))
143
				$retour = "\t" . $call($responseElement, $jqueryDone) . ";\n";
144
			else
145
				$retour = "\t{$responseElement}.{$jqueryDone}( data );\n";
146
		}
147
		if (isset($history)) {
148
			if ($this->params["autoActiveLinks"]) {
149
				$retour .= $this->autoActiveLinks("url");
150
			}
151
			$retour .= "\nwindow.history.pushState({'html':data,'selector':" . Javascript::prep_value($history) . ",'jqueryDone':'{$jqueryDone}'},'', url);";
152
		}
153
		if ($hasLoader === "internal") {
154
			$retour .= "\n$(self).removeClass('loading');";
155
		}
156
		$retour .= "\t" . $jsCallback . "\n";
157
		return $retour;
158
	}
159
160
	protected function _getResponseElement($responseElement) {
161
		if (JString::isNotNull($responseElement)) {
162
			$responseElement = Javascript::prep_jquery_selector($responseElement);
163
		}
164
		return $responseElement;
165
	}
166
167
	protected function _correctAjaxUrl($url) {
168
		if ($url !== "/" && JString::endsWith($url, "/") === true)
169
			$url = substr($url, 0, strlen($url) - 1);
170
		if (strncmp($url, 'http://', 7) != 0 && strncmp($url, 'https://', 8) != 0) {
171
			$url = $this->getUrl($url);
172
		}
173
		return $url;
174
	}
175
176
	public static function _correctParams($params, $ajaxParameters = []) {
177
		if (JString::isNull($params)) {
178
			return "";
179
		}
180
		if (\preg_match("@^\{.*?\}$@", $params)) {
181
			if (! isset($ajaxParameters['contentType']) || ! UString::contains('json', $ajaxParameters['contentType'])) {
182
				return '$.param(' . $params . ')';
183
			} else {
184
				return 'JSON.stringify(' . $params . ')';
185
			}
186
		}
187
		return $params;
188
	}
189
190
	public static function _implodeParams($parameters) {
191
		$allParameters = [];
192
		foreach ($parameters as $params) {
193
			if (isset($params))
194
				$allParameters[] = self::_correctParams($params);
195
		}
196
		return \implode("+'&'+", $allParameters);
197
	}
198
199
	protected function addLoading(&$retour, $responseElement, $ajaxLoader = null) {
200
		if (! isset($ajaxLoader)) {
201
			$ajaxLoader = $this->ajaxLoader;
202
		}
203
		$loading_notifier = '<div class="ajax-loader">' . $ajaxLoader . '</div>';
204
		$retour .= "{$responseElement}.empty();\n";
205
		$retour .= "\t\t{$responseElement}.prepend('{$loading_notifier}');\n";
206
	}
207
208
	protected function setAjaxDataCall($params) {
209
		$result = null;
210
		if (! \is_callable($params)) {
211
			$result = function ($responseElement, $jqueryDone = "html") use ($params) {
212
				return AjaxTransition::{$params}($responseElement, $jqueryDone);
213
			};
214
		}
215
		return $result;
216
	}
217
218
	protected function setDefaultParameters(&$parameters, $default) {
219
		foreach ($default as $k => $v) {
220
			if (! isset($parameters[$k]))
221
				$parameters[$k] = $v;
222
		}
223
	}
224
225
	public function setAjaxLoader($loader) {
226
		$this->ajaxLoader = $loader;
227
	}
228
229
	/**
230
	 * Performs an ajax GET request
231
	 *
232
	 * @param string $url
233
	 *        	The url of the request
234
	 * @param string $responseElement
235
	 *        	selector of the HTML element displaying the answer
236
	 */
237
	private function _get($url, $responseElement = "", $parameters = []) {
238
		return $this->_ajax("get", $url, $responseElement, $parameters);
239
	}
240
241
	/**
242
	 * Performs an ajax GET request
243
	 *
244
	 * @param string $url
245
	 *        	The url of the request
246
	 * @param string $responseElement
247
	 *        	selector of the HTML element displaying the answer
248
	 * @param array $parameters
249
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
250
	 */
251
	public function get($url, $responseElement = "", $parameters = []) {
252
		$parameters["immediatly"] = true;
253
		return $this->_get($url, $responseElement, $parameters);
254
	}
255
256
	/**
257
	 * Performs an ajax request
258
	 *
259
	 * @param string $method
260
	 *        	The http method (get, post, delete, put, head)
261
	 * @param string $url
262
	 *        	The url of the request
263
	 * @param string $responseElement
264
	 *        	selector of the HTML element displaying the answer
265
	 * @param array $parameters
266
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
267
	 */
268
	public function ajax($method, $url, $responseElement = "", $parameters = []) {
269
		$parameters["immediatly"] = true;
270
		return $this->_ajax($method, $url, $responseElement, $parameters);
271
	}
272
273
	/**
274
	 * Executes an ajax query at regular intervals
275
	 *
276
	 * @param string $method
277
	 *        	The http method (post, get...)
278
	 * @param string $url
279
	 *        	The url of the request
280
	 * @param int $interval
281
	 *        	The interval in milliseconds
282
	 * @param string $globalName
283
	 *        	The interval name, for clear it
284
	 * @param string $responseElement
285
	 * @param array $parameters
286
	 *        	The ajax parameters, default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
287
	 * @return string
288
	 */
289
	public function ajaxInterval($method, $url, $interval, $globalName = null, $responseElement = "", $parameters = []) {
290
		return $this->interval($this->ajaxDeferred($method, $url, $responseElement, $parameters), $interval, $globalName);
291
	}
292
293
	/**
294
	 * Performs a deferred ajax request
295
	 *
296
	 * @param string $method
297
	 *        	The http method (get, post, delete, put, head)
298
	 * @param string $url
299
	 *        	The url of the request
300
	 * @param string $responseElement
301
	 *        	selector of the HTML element displaying the answer
302
	 * @param array $parameters
303
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
304
	 */
305
	public function ajaxDeferred($method, $url, $responseElement = "", $parameters = []) {
306
		$parameters["immediatly"] = false;
307
		return $this->_ajax($method, $url, $responseElement, $parameters);
308
	}
309
310
	/**
311
	 * Performs an ajax request and receives the JSON data types by assigning DOM elements with the same name
312
	 *
313
	 * @param string $url
314
	 *        	the request url
315
	 * @param string $method
316
	 *        	Method used
317
	 * @param array $parameters
318
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
319
	 */
320
	private function _json($url, $method = "get", $parameters = []) {
321
		$parameters = \array_merge($parameters, [
322
			"hasLoader" => false
323
		]);
324
		$jsCallback = isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
325
		$context = isset($parameters['context']) ? $parameters['context'] : "document";
326
		$retour = "\tdata=($.isPlainObject(data))?data:JSON.parse(data);\t" . $jsCallback . ";" . "\n\tfor(var key in data){" . "if($('#'+key," . $context . ").length){ if($('#'+key," . $context . ").is('[value]')) { $('#'+key," . $context . ").val(data[key]);} else { $('#'+key," . $context . ").html(data[key]); }}};\n";
327
		$retour .= "\t$(document).trigger('jsonReady',[data]);\n";
328
		$parameters["jsCallback"] = $retour;
329
		return $this->_ajax($method, $url, null, $parameters);
330
	}
331
332
	/**
333
	 * Performs an ajax request and receives the JSON data types by assigning DOM elements with the same name
334
	 *
335
	 * @param string $url
336
	 *        	the request url
337
	 * @param string $method
338
	 *        	Method used
339
	 * @param array $parameters
340
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
341
	 */
342
	public function json($url, $method = "get", $parameters = []) {
343
		return $this->_json($url, $method, $parameters);
344
	}
345
346
	/**
347
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
348
	 *
349
	 * @param string $element
350
	 * @param string $event
351
	 * @param string $url
352
	 *        	the request address
353
	 * @param string $method
354
	 *        	default get
355
	 * @param array $parameters
356
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
357
	 */
358
	public function jsonOn($event, $element, $url, $method = "get", $parameters = array()) {
359
		$this->setDefaultParameters($parameters, [
360
			"preventDefault" => true,
361
			"stopPropagation" => true,
362
			"immediatly" => true
363
		]);
364
		return $this->_add_event($element, $this->jsonDeferred($url, $method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"], $parameters["immediatly"]);
365
	}
366
367
	/**
368
	 * Prepares an ajax request delayed and receives the JSON data types by assigning DOM elements with the same name
369
	 *
370
	 * @param string $url
371
	 *        	the request url
372
	 * @param string $method
373
	 *        	Method used
374
	 * @param array $parameters
375
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
376
	 */
377
	public function jsonDeferred($url, $method = "get", $parameters = []) {
378
		$parameters["immediatly"] = false;
379
		return $this->_json($url, $method, $parameters);
380
	}
381
382
	/**
383
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name
384
	 *
385
	 * @param string $maskSelector
386
	 * @param string $url
387
	 *        	the request url
388
	 * @param string $method
389
	 *        	Method used, default : get
390
	 * @param array $parameters
391
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"immediatly"=>false,"rowClass"=>"_json")
392
	 */
393
	private function _jsonArray($maskSelector, $url, $method = "get", $parameters = []) {
394
		$parameters = \array_merge($parameters, [
395
			"hasLoader" => false
396
		]);
397
		$rowClass = isset($parameters['rowClass']) ? $parameters['rowClass'] : "_json";
398
		$jsCallback = isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
399
		$context = isset($parameters['context']) ? $parameters['context'] : null;
400
		if ($context === null) {
401
			$parent = "$('" . $maskSelector . "').parent()";
402
			$newElm = "$('#'+newId)";
403
		} else {
404
			$parent = $context;
405
			$newElm = $context . ".find('#'+newId)";
406
		}
407
		$appendTo = "\t\tnewElm.appendTo(" . $parent . ");\n";
408
		$retour = $parent . ".find('.{$rowClass}').remove();";
409
		$retour .= "\tdata=($.isPlainObject(data)||$.isArray(data))?data:JSON.parse(data);\n$.each(data, function(index, value) {\n" . "\tvar created=false;var maskElm=$('" . $maskSelector . "').first();maskElm.hide();" . "\tvar newId=(maskElm.attr('id') || 'mask')+'-'+index;" . "\tvar newElm=" . $newElm . ";\n" . "\tif(!newElm.length){\n" . "\t\tnewElm=maskElm.clone();
410
		newElm.attr('id',newId);\n;newElm.addClass('{$rowClass}').removeClass('_jsonArrayModel');\nnewElm.find('[id]').each(function(){ var newId=$(this).attr('id')+'-'+index;$(this).attr('id',newId).removeClass('_jsonArrayChecked');});\n";
411
		$retour .= $appendTo;
412
		$retour .= "\t}\n" . "\tfor(var key in value){\n" . "\t\t\tvar html = $('<div />').append($(newElm).clone()).html();\n" . "\t\t\tif(html.indexOf('__'+key+'__')>-1){\n" . "\t\t\t\tcontent=$(html.split('__'+key+'__').join(value[key]));\n" . "\t\t\t\t$(newElm).replaceWith(content);newElm=content;\n" . "\t\t\t}\n" . "\t\tvar sel='[data-id=\"'+key+'\"]';if($(sel,newElm).length){\n" . "\t\t\tvar selElm=$(sel,newElm);\n" . "\t\t\t if(selElm.is('[value]')) { selElm.attr('value',value[key]);selElm.val(value[key]);} else { selElm.html(value[key]); }\n" . "\t\t}\n" . "}\n" . "\t$(newElm).show(true);" . "\n" . "\t$(newElm).removeClass('hide');" . "});\n";
413
		$retour .= "\t$(document).trigger('jsonReady',[data]);\n";
414
		$retour .= "\t" . $jsCallback;
415
		$parameters["jsCallback"] = $retour;
416
		return $this->_ajax($method, $url, null, $parameters);
417
	}
418
419
	/**
420
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name
421
	 *
422
	 * @param string $maskSelector
423
	 * @param string $url
424
	 *        	the request url
425
	 * @param string $method
426
	 *        	Method used, default : get
427
	 * @param array $parameters
428
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"immediatly"=>false,"rowClass"=>"_json")
429
	 */
430
	public function jsonArray($maskSelector, $url, $method = "get", $parameters = []) {
431
		return $this->_jsonArray($maskSelector, $url, $method, $parameters);
432
	}
433
434
	/**
435
	 * Peforms an ajax request delayed and receives a JSON array data types by copying and assigning them to the DOM elements with the same name
436
	 *
437
	 * @param string $maskSelector
438
	 * @param string $url
439
	 *        	the request url
440
	 * @param string $method
441
	 *        	Method used, default : get
442
	 * @param array $parameters
443
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"rowClass"=>"_json")
444
	 */
445
	public function jsonArrayDeferred($maskSelector, $url, $method = "get", $parameters) {
446
		$parameters["immediatly"] = false;
447
		return $this->jsonArray($maskSelector, $url, $method, $parameters);
448
	}
449
450
	/**
451
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name when $event fired on $element
452
	 *
453
	 * @param string $element
454
	 * @param string $event
455
	 * @param string $url
456
	 *        	the request url
457
	 * @param string $method
458
	 *        	Method used, default : get
459
	 * @param array $parameters
460
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","rowClass"=>"_json","immediatly"=>true)
461
	 */
462
	public function jsonArrayOn($event, $element, $maskSelector, $url, $method = "get", $parameters = array()) {
463
		$this->setDefaultParameters($parameters, [
464
			"preventDefault" => true,
465
			"stopPropagation" => true,
466
			"immediatly" => true
467
		]);
468
		return $this->_add_event($element, $this->jsonArrayDeferred($maskSelector, $url, $method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"], $parameters["immediatly"]);
469
	}
470
471
	/**
472
	 * Prepares a Get ajax request
473
	 * for using on an event
474
	 *
475
	 * @param string $url
476
	 *        	The url of the request
477
	 * @param string $responseElement
478
	 *        	selector of the HTML element displaying the answer
479
	 * @param array $parameters
480
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
481
	 */
482
	public function getDeferred($url, $responseElement = "", $parameters = []) {
483
		$parameters["immediatly"] = false;
484
		return $this->_get($url, $responseElement, $parameters);
485
	}
486
487
	/**
488
	 * Performs a get to $url on the event $event on $element
489
	 * and display it in $responseElement
490
	 *
491
	 * @param string $event
492
	 *        	the event
493
	 * @param string $element
494
	 *        	the element on which event is observed
495
	 * @param string $url
496
	 *        	The url of the request
497
	 * @param string $responseElement
498
	 *        	The selector of the HTML element displaying the answer
499
	 * @param array $parameters
500
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>null,"headers"=>null,"historize"=>false)
501
	 */
502
	public function getOn($event, $element, $url, $responseElement = "", $parameters = array()) {
503
		$this->setDefaultParameters($parameters, [
504
			"preventDefault" => true,
505
			"stopPropagation" => true,
506
			"immediatly" => true
507
		]);
508
		return $this->_add_event($element, $this->getDeferred($url, $responseElement, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"], $parameters["immediatly"]);
509
	}
510
511
	/**
512
	 * Performs an ajax request to $url on the event $event on $element
513
	 * and display it in $responseElement
514
	 *
515
	 * @param string $event
516
	 *        	the event observed
517
	 * @param string $element
518
	 *        	the element on which event is observed
519
	 * @param string $url
520
	 *        	The url of the request
521
	 * @param string $responseElement
522
	 *        	The selector of the HTML element displaying the answer
523
	 * @param array $parameters
524
	 *        	default : array("method"=>"get","preventDefault"=>true,"stopPropagation"=>true,"params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","jsCondition"=>NULL,"headers"=>null,"historize"=>false)
525
	 */
526
	public function ajaxOn($event, $element, $url, $responseElement = "", $parameters = array()) {
527
		$this->setDefaultParameters($parameters, [
528
			"preventDefault" => true,
529
			"stopPropagation" => true,
530
			"immediatly" => true,
531
			"method" => "get"
532
		]);
533
		return $this->_add_event($element, $this->ajaxDeferred($parameters["method"], $url, $responseElement, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"], $parameters["immediatly"]);
534
	}
535
536
	/**
537
	 * Performs a get to $url on the click event on $element
538
	 * and display it in $responseElement
539
	 *
540
	 * @param string $element
541
	 *        	the element on which event is observed
542
	 * @param string $url
543
	 *        	The url of the request
544
	 * @param string $responseElement
545
	 *        	The selector of the HTML element displaying the answer
546
	 * @param array $parameters
547
	 *        	default : array("method"=>"get","preventDefault"=>true,"stopPropagation"=>true,"params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","jsCondition"=>NULL,"headers"=>null,"historize"=>false)
548
	 */
549
	public function ajaxOnClick($element, $url, $responseElement = "", $parameters = array()) {
550
		return $this->ajaxOn("click", $element, $url, $responseElement, $parameters);
551
	}
552
553
	/**
554
	 * Performs a get to $url on the click event on $element
555
	 * and display it in $responseElement
556
	 *
557
	 * @param string $element
558
	 *        	the element on which click is observed
559
	 * @param string $url
560
	 *        	The url of the request
561
	 * @param string $responseElement
562
	 *        	The selector of the HTML element displaying the answer
563
	 * @param array $parameters
564
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","jsCondition"=>NULL,"headers"=>null,"historize"=>false)
565
	 */
566
	public function getOnClick($element, $url, $responseElement = "", $parameters = array()) {
567
		return $this->getOn("click", $element, $url, $responseElement, $parameters);
568
	}
569
570
	/**
571
	 * Uses an hyperlink to make an ajax get request
572
	 *
573
	 * @param string $element
574
	 *        	an hyperlink selector
575
	 * @param string $responseElement
576
	 *        	the target of the ajax request (data-target attribute of the element is used if responseElement is omited)
577
	 * @param array $parameters
578
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"params"=>"{}","jsCallback"=>NULL,"attr"=>"href","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","jsCondition"=>NULL,"headers"=>null,"historize"=>true)
579
	 * @return $this
580
	 */
581
	public function getHref($element, $responseElement = "", $parameters = array()) {
582
		$parameters["attr"] = "href";
583
		if (JString::isNull($responseElement)) {
584
			$responseElement = '%$(self).attr("data-target")%';
585
		}
586
		if (! isset($parameters["historize"])) {
587
			$parameters["historize"] = true;
588
		}
589
		return $this->getOnClick($element, "", $responseElement, $parameters);
590
	}
591
592
	/**
593
	 * Uses an hyperlink to make an ajax get request
594
	 *
595
	 * @param string $element
596
	 *        	an hyperlink selector
597
	 * @param string $responseElement
598
	 *        	the target of the ajax request (data-target attribute of the element is used if responseElement is omited)
599
	 * @param array $parameters
600
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"params"=>"{}","jsCallback"=>NULL,"attr"=>"href","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","jsCondition"=>NULL,"headers"=>null,"historize"=>false)
601
	 * @return $this
602
	 */
603
	public function postHref($element, $responseElement = "", $parameters = array()) {
604
		$parameters["attr"] = "href";
605
		if (JString::isNull($responseElement)) {
606
			$responseElement = '%$(this).attr("data-target")%';
607
		}
608
		if (! isset($parameters["historize"])) {
609
			$parameters["historize"] = true;
610
		}
611
		return $this->postOnClick($element, "", "{}", $responseElement, $parameters);
612
	}
613
614
	private function _post($url, $params = "{}", $responseElement = "", $parameters = []) {
615
		$parameters["params"] = $params;
616
		return $this->_ajax("POST", $url, $responseElement, $parameters);
617
	}
618
619
	/**
620
	 * Makes an ajax post
621
	 *
622
	 * @param string $url
623
	 *        	the request url
624
	 * @param string $responseElement
625
	 *        	selector of the HTML element displaying the answer
626
	 * @param string $params
627
	 *        	JSON parameters
628
	 * @param array $parameters
629
	 *        	default : array("jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
630
	 */
631
	public function post($url, $params = "{}", $responseElement = "", $parameters = []) {
632
		return $this->_post($url, $params, $responseElement, $parameters);
633
	}
634
635
	/**
636
	 * Prepares a delayed ajax POST
637
	 * to use on an event
638
	 *
639
	 * @param string $url
640
	 *        	the request url
641
	 * @param string $params
642
	 *        	JSON parameters
643
	 * @param string $responseElement
644
	 *        	selector of the HTML element displaying the answer
645
	 * @param array $parameters
646
	 *        	default : array("jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
647
	 */
648
	public function postDeferred($url, $params = "{}", $responseElement = "", $parameters = []) {
649
		$parameters["immediatly"] = false;
650
		return $this->_post($url, $params, $responseElement, $parameters);
651
	}
652
653
	/**
654
	 * Performs a post to $url on the event $event fired on $element and pass the parameters $params
655
	 * Display the result in $responseElement
656
	 *
657
	 * @param string $event
658
	 * @param string $element
659
	 * @param string $url
660
	 *        	The url of the request
661
	 * @param string $params
662
	 *        	The parameters to send
663
	 * @param string $responseElement
664
	 *        	selector of the HTML element displaying the answer
665
	 * @param array $parameters
666
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
667
	 */
668
	public function postOn($event, $element, $url, $params = "{}", $responseElement = "", $parameters = array()) {
669
		$this->setDefaultParameters($parameters, [
670
			"preventDefault" => true,
671
			"stopPropagation" => true,
672
			"immediatly" => true
673
		]);
674
		return $this->_add_event($element, $this->postDeferred($url, $params, $responseElement, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"], $parameters["immediatly"]);
675
	}
676
677
	/**
678
	 * Performs a post to $url on the click event fired on $element and pass the parameters $params
679
	 * Display the result in $responseElement
680
	 *
681
	 * @param string $element
682
	 * @param string $url
683
	 *        	The url of the request
684
	 * @param string $params
685
	 *        	The parameters to send
686
	 * @param string $responseElement
687
	 *        	selector of the HTML element displaying the answer
688
	 * @param array $parameters
689
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
690
	 */
691
	public function postOnClick($element, $url, $params = "{}", $responseElement = "", $parameters = array()) {
692
		return $this->postOn("click", $element, $url, $params, $responseElement, $parameters);
693
	}
694
695
	private function _postForm($url, $form, $responseElement, $parameters = []) {
696
		if (isset($this->params["ajax"])) {
697
			extract($this->params["ajax"]);
698
		}
699
		$params = "{}";
700
		$validation = false;
701
		$hasFiles = false;
702
		\extract($parameters);
703
		$async = ($async) ? "true" : "false";
704
		$jsCallback = isset($jsCallback) ? $jsCallback : "";
705
		$retour = $this->_getAjaxUrl($url, $attr);
706
		$retour .= "\n$('#" . $form . "').trigger('ajaxSubmit');";
707
		if (! $hasFiles) {
0 ignored issues
show
introduced by
The condition $hasFiles is always false.
Loading history...
708
			$retour .= "\nvar params=$('#" . $form . "').serialize();\n";
709
			if (isset($params)) {
710
				$retour .= "params+='&'+" . self::_correctParams($params) . ";\n";
711
			}
712
			$ajaxParameters = [];
713
		} else {
714
			$retour .= "\nvar params=new FormData($('#" . $form . "')[0]);\n";
715
			$ajaxParameters = [
716
				'enctype' => "'multipart/form-data'",
717
				'processData' => "false",
718
				'contentType' => "false",
719
				'timeout' => 600000
720
			];
721
		}
722
		$responseElement = $this->_getResponseElement($responseElement);
723
		$retour .= "var self=this;\n";
724
		if ($hasLoader === true) {
725
			$this->addLoading($retour, $responseElement, $ajaxLoader);
726
		} elseif ($hasLoader === "internal") {
727
			$retour .= "\n$(this).addClass('loading');";
728
		}
729
		$ajaxParameters = [
730
			"url" => "url",
731
			"method" => "'POST'",
732
			"data" => "params",
733
			"async" => $async
734
		] + $ajaxParameters;
735
		if (isset($headers)) {
736
			$ajaxParameters["headers"] = $headers;
737
		}
738
		$this->createAjaxParameters($ajaxParameters, $parameters);
739
		$retour .= "$.ajax({" . $this->implodeAjaxParameters($ajaxParameters) . "}).done(function( data ) {\n";
740
		$retour .= $this->_getOnAjaxDone($responseElement, $jqueryDone, $ajaxTransition, $jsCallback, $hasLoader) . "});\n";
741
742
		if ($validation) {
0 ignored issues
show
introduced by
The condition $validation is always false.
Loading history...
743
			$retour = "$('#" . $form . "').validate({submitHandler: function(form) {
744
			" . $retour . "
745
			}});\n";
746
			$retour .= "$('#" . $form . "').submit();\n";
747
		}
748
		$retour = $this->_addJsCondition($jsCondition, $retour);
749
		if ($immediatly)
750
			$this->jquery_code_for_compile[] = $retour;
751
		return $retour;
752
	}
753
754
	/**
755
	 * Performs a post form with ajax
756
	 *
757
	 * @param string $url
758
	 *        	The url of the request
759
	 * @param string $form
760
	 *        	The form HTML id
761
	 * @param string $responseElement
762
	 *        	selector of the HTML element displaying the answer
763
	 * @param array $parameters
764
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
765
	 */
766
	public function postForm($url, $form, $responseElement, $parameters = []) {
767
		$parameters["immediatly"] = true;
768
		return $this->_postForm($url, $form, $responseElement, $parameters);
769
	}
770
771
	/**
772
	 * Performs a delayed post form with ajax
773
	 * For use on an event
774
	 *
775
	 * @param string $url
776
	 *        	The url of the request
777
	 * @param string $form
778
	 *        	The form HTML id
779
	 * @param string $responseElement
780
	 *        	selector of the HTML element displaying the answer
781
	 * @param array $parameters
782
	 *        	default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
783
	 */
784
	public function postFormDeferred($url, $form, $responseElement, $parameters = []) {
785
		$parameters["immediatly"] = false;
786
		return $this->_postForm($url, $form, $responseElement, $parameters);
787
	}
788
789
	/**
790
	 * Performs a post form with ajax in response to an event $event on $element
791
	 * display the result in $responseElement
792
	 *
793
	 * @param string $event
794
	 * @param string $element
795
	 * @param string $url
796
	 * @param string $form
797
	 * @param string $responseElement
798
	 *        	selector of the HTML element displaying the answer
799
	 * @param array $parameters
800
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"validation"=>false,"params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>null,"headers"=>null,"historize"=>false)
801
	 */
802
	public function postFormOn($event, $element, $url, $form, $responseElement = "", $parameters = array()) {
803
		$this->setDefaultParameters($parameters, [
804
			"preventDefault" => true,
805
			"stopPropagation" => true,
806
			"immediatly" => true
807
		]);
808
		return $this->_add_event($element, $this->postFormDeferred($url, $form, $responseElement, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"], $parameters["immediatly"]);
809
	}
810
811
	/**
812
	 * Performs a post form with ajax in response to the click event on $element
813
	 * display the result in $responseElement
814
	 *
815
	 * @param string $element
816
	 * @param string $url
817
	 * @param string $form
818
	 * @param string $responseElement
819
	 *        	selector of the HTML element displaying the answer
820
	 * @param array $parameters
821
	 *        	default : array("preventDefault"=>true,"stopPropagation"=>true,"validation"=>false,"params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>null,"headers"=>null,"historize"=>false)
822
	 */
823
	public function postFormOnClick($element, $url, $form, $responseElement = "", $parameters = array()) {
824
		return $this->postFormOn("click", $element, $url, $form, $responseElement, $parameters);
825
	}
826
}
827