Passed
Push — master ( f2c7af...346e2d )
by Jean-Christophe
02:19
created

JsUtilsAjaxTrait::_getFormElement()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 3
c 0
b 0
f 0
nc 2
nop 1
dl 0
loc 5
rs 10
1
<?php
2
namespace Ajax\common\traits;
3
4
use Ajax\service\AjaxTransition;
5
use Ajax\service\JString;
6
use Ajax\service\Javascript;
7
8
/**
9
 *
10
 * @author jc
11
 * @property array $jquery_code_for_compile
12
 * @property array $params
13
 */
14
trait JsUtilsAjaxTrait {
15
16
	protected $ajaxTransition;
17
18
	protected $ajaxLoader = "<div class=\"ui active centered inline text loader\">Loading</div>";
19
20
	abstract public function getUrl($url);
21
22
	abstract public function _add_event($element, $js, $event, $preventDefault = false, $stopPropagation = false, $immediatly = true, $listenerOn = false);
23
24
	abstract public function interval($jsCode, $time, $globalName = null, $immediatly = true);
25
26
	protected function _ajax($method, $url, $responseElement = '', $parameters = []) {
27
		if (isset($this->params['ajax'])) {
28
			extract($this->params['ajax']);
29
		}
30
		extract($parameters);
31
32
		$jsCallback = isset($jsCallback) ? $jsCallback : '';
33
		$retour = $this->_getAjaxUrl($url, $attr);
34
		$originalSelector = $responseElement;
35
		$responseElement = $this->_getResponseElement($responseElement);
36
		$retour .= "var self=this;\n";
37
		$before = isset($before) ? $before : "";
38
		$retour .= $before;
39
		if ($hasLoader === true && JString::isNotNull($responseElement)) {
40
			$this->addLoading($retour, $responseElement, $ajaxLoader);
41
		} elseif ($hasLoader === 'response') {
42
			$this->addResponseLoading($retour, $responseElement, $ajaxLoader);
43
		} elseif ($hasLoader === 'internal-x') {
44
			$this->addLoading($retour, '$(this).closest(".item, .step")', $ajaxLoader);
45
		} elseif ($hasLoader === 'internal') {
46
			$retour .= "\n$(this).addClass('loading');";
47
		} elseif (\is_string($hasLoader)) {
48
			$this->addLoading($retour, $hasLoader, $ajaxLoader);
49
		}
50
		$ajaxParameters = [
51
			"url" => "url",
52
			"method" => "'" . \strtoupper($method) . "'"
53
		];
54
55
		$ajaxParameters["async"] = ($async ? "true" : "false");
56
57
		if (isset($params)) {
58
			$ajaxParameters["data"] = self::_correctParams($params, $parameters);
59
		}
60
		if (isset($headers)) {
61
			$ajaxParameters["headers"] = $headers;
62
		}
63
		if ($csrf) {
64
			$csrf = (is_string($csrf)) ? $csrf : 'csrf-token';
65
			$parameters["beforeSend"] = "jqXHR.setRequestHeader('{$csrf}', $('meta[name=\"{$csrf}\"]').attr('content'));";
66
		}
67
		if (isset($partial)) {
68
			$ajaxParameters["xhr"] = "xhrProvider";
69
			$retour .= "var xhr = $.ajaxSettings.xhr();function xhrProvider() {return xhr;};xhr.onreadystatechange = function (e) { if (3==e.target.readyState){let response=e.target.responseText;" . $partial . ";}; };";
70
		}
71
		$this->createAjaxParameters($ajaxParameters, $parameters);
72
		$retour .= "$.ajax({" . $this->implodeAjaxParameters($ajaxParameters) . "}).done(function( data, textStatus, jqXHR ) {\n";
73
		$retour .= $this->_getOnAjaxDone($responseElement, $jqueryDone, $ajaxTransition, $jsCallback, $hasLoader, ($historize ? $originalSelector : null)) . "});\n";
74
75
		$retour = $this->_addJsCondition($jsCondition, $retour);
76
		if ($immediatly)
77
			$this->jquery_code_for_compile[] = $retour;
78
		return $retour;
79
	}
80
81
	protected function createAjaxParameters(&$original, $parameters) {
82
		$validParameters = [
83
			"contentType" => "%value%",
84
			"dataType" => "'%value%'",
85
			"beforeSend" => "function(jqXHR,settings){%value%}",
86
			"complete" => "function(jqXHR){%value%}",
87
			"processData" => "%value%"
88
		];
89
		foreach ($validParameters as $param => $mask) {
90
			if (isset($parameters[$param])) {
91
				$original[$param] = \str_replace("%value%", $parameters[$param], $mask);
92
			}
93
		}
94
	}
95
96
	protected function implodeAjaxParameters($ajaxParameters) {
97
		$s = '';
98
		foreach ($ajaxParameters as $k => $v) {
99
			if ($s !== '') {
100
				$s .= ',';
101
			}
102
			if (is_array($v)) {
103
				$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

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