Passed
Push — master ( 52e3ac...33a902 )
by Jean-Christophe
02:15
created

JsUtilsAjaxTrait::onPopstate()   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 0
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace Ajax\common\traits;
4
5
use Ajax\service\AjaxTransition;
6
use Ajax\service\Javascript;
7
use Ajax\service\JString;
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
	protected $ajaxLoader="<div class=\"ui active centered inline text loader\">Loading</div>";
18
19
	abstract public function getUrl($url);
20
	abstract public function _add_event($element, $js, $event, $preventDefault=false, $stopPropagation=false,$immediatly=true);
21
22
	protected function _ajax($method,$url,$responseElement="",$parameters=[]) {
23
		if(isset($this->params["ajax"])){
24
			extract($this->params["ajax"]);
25
		}
26
		extract($parameters);
27
28
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
29
		$retour=$this->_getAjaxUrl($url, $attr);
30
		$originalSelector=$responseElement;
31
		$responseElement=$this->_getResponseElement($responseElement);
32
		$retour.="var self=this;\n";
33
		if($hasLoader===true && JString::isNotNull($responseElement)){
34
			$this->addLoading($retour, $responseElement,$ajaxLoader);
35
		}elseif($hasLoader==="internal"){
36
			$retour.="\n$(this).addClass('loading');";
37
		}
38
		$ajaxParameters=["url"=>"url","method"=>"'".\strtoupper($method)."'"];
39
		
40
		$ajaxParameters["async"]=($async?"true":"false");
41
		
42
		if(isset($params)){
43
			$ajaxParameters["data"]=self::_correctParams($params);
44
		}
45
		if(isset($headers)){
46
			$ajaxParameters["headers"]=$headers;
47
		}
48
		$this->createAjaxParameters($ajaxParameters, $parameters);
49
		$retour.="$.ajax({".$this->implodeAjaxParameters($ajaxParameters)."}).done(function( data, textStatus, jqXHR ) {\n";
50
		$retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$ajaxTransition,$jsCallback,$hasLoader,($historize?$originalSelector:null))."});\n";
51
		$retour=$this->_addJsCondition($jsCondition,$retour);
52
		if ($immediatly)
53
			$this->jquery_code_for_compile[]=$retour;
54
		return $retour;
55
	}
56
57
	protected function createAjaxParameters(&$original,$parameters){
58
		$validParameters=["dataType"=>"'%value%'","beforeSend"=>"function(jqXHR,settings){%value%}","complete"=>"function(jqXHR){%value%}"];
59
		foreach ($validParameters as $param=>$mask){
60
			if(isset($parameters[$param])){
61
				$original[$param]=\str_replace("%value%", $parameters[$param], $mask);
62
			}
63
		}
64
	}
65
66
	protected function implodeAjaxParameters($ajaxParameters){
67
		$s = ''; foreach ($ajaxParameters as $k=>$v) { if ($s !== '') { $s .= ','; } $s .= "'{$k}':{$v}"; }
68
		return $s;
69
	}
70
71
	protected function _addJsCondition($jsCondition,$jsSource){
72
		if(isset($jsCondition)){
73
			return "if(".$jsCondition."){\n".$jsSource."\n}";
74
		}
75
		return $jsSource;
76
	}
77
78
79
	protected function _getAjaxUrl($url,$attr){
80
		$url=$this->_correctAjaxUrl($url);
81
		$retour="url='".$url."';";
82
		$slash="/";
83
		if(JString::endswith($url, "/")===true){
84
			$slash="";
85
		}
86
		if(JString::isNotNull($attr)){
87
			if ($attr==="value"){
88
				$retour.="url=url+'".$slash."'+$(this).val();\n";
89
			}elseif ($attr==="html"){
90
				$retour.="url=url+'".$slash."'+$(this).html();\n";
91
			}elseif(\substr($attr, 0,3)==="js:"){
92
				$retour.="url=url+'".$slash."'+".\substr($attr, 3).";\n";
93
			}elseif($attr!==null && $attr!=="")
94
				$retour.="url=url+'".$slash."'+($(this).attr('".$attr."')||'');\n";
95
		}
96
		return $retour;
97
	}
98
	
99
	protected function onPopstate(){
100
		return "window.onpopstate = function(e){if(e.state){var target=e.state.jqueryDone;$(e.state.selector)[target](e.state.html);}};";
101
	}
102
103
	protected function _getOnAjaxDone($responseElement,$jqueryDone,$ajaxTransition,$jsCallback,$hasLoader=false,$history=null){
104
		$retour="";$call=null;
105
		if (JString::isNotNull($responseElement)) {
106
			if(isset($ajaxTransition)){
107
				$call=$this->setAjaxDataCall($ajaxTransition);
108
			}elseif(isset($this->ajaxTransition)){
109
				$call=$this->ajaxTransition;
110
			}
111
			if(\is_callable($call))
112
				$retour="\t".$call($responseElement,$jqueryDone).";\n";
113
			else
114
				$retour="\t{$responseElement}.{$jqueryDone}( data );\n";
115
		}
116
		if(isset($history)){
117
			$retour.="\nwindow.history.pushState({'html':data,'selector':".Javascript::prep_value($history).",'jqueryDone':'{$jqueryDone}'},'', url);";
118
		}
119
		if($hasLoader==="internal"){
120
			$retour.="\n$(self).removeClass('loading');";
121
		}
122
		$retour.="\t".$jsCallback."\n";
123
		return $retour;
124
	}
125
126
	protected function _getResponseElement($responseElement){
127
		if (JString::isNotNull($responseElement)) {
128
			$responseElement=Javascript::prep_value($responseElement);
129
			$responseElement=Javascript::prep_jquery_selector($responseElement);
130
		}
131
		return $responseElement;
132
	}
133
134
	protected function _correctAjaxUrl($url) {
135
		if ($url!=="/" && JString::endsWith($url, "/")===true)
136
			$url=substr($url, 0, strlen($url)-1);
137
			if (strncmp($url, 'http://', 7)!=0&&strncmp($url, 'https://', 8)!=0) {
138
				$url=$this->getUrl($url);
139
			}
140
			return $url;
141
	}
142
143
	public static function _correctParams($params){
144
		if(JString::isNull($params)){
145
			return "";
146
		}
147
		if(\preg_match("@^\{.*?\}$@", $params)){
148
			return '$.param('.$params.')';
149
		}
150
		return $params;
151
	}
152
153
	public static function _implodeParams($parameters){
154
		$allParameters=[];
155
		foreach ($parameters as $params){
156
			if(isset($params))
157
				$allParameters[]=self::_correctParams($params);
158
		}
159
		return \implode("+'&'+", $allParameters);
160
	}
161
162
	protected function addLoading(&$retour, $responseElement,$ajaxLoader=null) {
163
		if(!isset($ajaxLoader)){
164
			$ajaxLoader=$this->ajaxLoader;
165
		}
166
		$loading_notifier='<div class="ajax-loader">'.$ajaxLoader.'</div>';
167
		$retour.="{$responseElement}.empty();\n";
168
		$retour.="\t\t{$responseElement}.prepend('{$loading_notifier}');\n";
169
	}
170
171
	protected function setAjaxDataCall($params){
172
		$result=null;
173
		if(!\is_callable($params)){
174
			$result=function ($responseElement,$jqueryDone="html") use($params){
175
				return AjaxTransition::{$params}($responseElement,$jqueryDone);
176
			};
177
		}
178
		return $result;
179
	}
180
181
	protected function setDefaultParameters(&$parameters,$default){
182
		foreach ($default as $k=>$v){
183
			if(!isset($parameters[$k]))
184
				$parameters[$k]=$v;
185
		}
186
	}
187
188
	public function setAjaxLoader($loader) {
189
		$this->ajaxLoader=$loader;
190
	}
191
192
	/**
193
	 * Performs an ajax GET request
194
	 * @param string $url The url of the request
195
	 * @param string $responseElement selector of the HTML element displaying the answer
196
	 */
197
	private function _get($url, $responseElement="",$parameters=[]) {
198
		return $this->_ajax("get", $url,$responseElement,$parameters);
199
	}
200
201
	/**
202
	 * Performs an ajax GET request
203
	 * @param string $url The url of the request
204
	 * @param string $responseElement selector of the HTML element displaying the answer
205
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
206
	 */
207
	public function get($url, $responseElement="",$parameters=[]) {
208
		$parameters["immediatly"]=true;
209
		return $this->_get($url,$responseElement,$parameters);
210
	}
211
212
	/**
213
	 * Performs an ajax request
214
	 * @param string $method The http method (get, post, delete, put, head)
215
	 * @param string $url The url of the request
216
	 * @param string $responseElement selector of the HTML element displaying the answer
217
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
218
	 */
219
	public function ajax($method,$url, $responseElement="", $parameters=[]) {
220
		$parameters["immediatly"]=true;
221
		return $this->_ajax($method,$url,$responseElement,$parameters);
222
	}
223
224
	/**
225
	 * Performs a deferred ajax request
226
	 * @param string $method The http method (get, post, delete, put, head)
227
	 * @param string $url The url of the request
228
	 * @param string $responseElement selector of the HTML element displaying the answer
229
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
230
	 */
231
	public function ajaxDeferred($method,$url, $responseElement="", $parameters=[]) {
232
		$parameters["immediatly"]=false;
233
		return $this->_ajax($method,$url,$responseElement,$parameters);
234
	}
235
236
	/**
237
	 * Performs an ajax request and receives the JSON data types by assigning DOM elements with the same name
238
	 * @param string $url the request url
239
	 * @param string $method Method used
240
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
241
	 */
242
	private function _json($url, $method="get",$parameters=[]) {
243
		$parameters=\array_merge($parameters,["hasLoader"=>false]);
244
		$jsCallback=isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
245
		$context=isset($parameters['context']) ? $parameters['context'] : "document";
246
		$retour="\tdata=($.isPlainObject(data))?data:JSON.parse(data);\t".$jsCallback.";\n\tfor(var key in data){"
247
				."if($('#'+key,".$context.").length){ if($('#'+key,".$context.").is('[value]')) { $('#'+key,".$context.").val(data[key]);} else { $('#'+key,".$context.").html(data[key]); }}};\n";
248
				$retour.="\t$(document).trigger('jsonReady',[data]);\n";
249
		$parameters["jsCallback"]=$retour;
250
		return $this->_ajax($method, $url,null,$parameters);
251
	}
252
253
	/**
254
	 * Performs an ajax request and receives the JSON data types by assigning DOM elements with the same name
255
	 * @param string $url the request url
256
	 * @param string $method Method used
257
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
258
	 */
259
	public function json($url, $method="get", $parameters=[]) {
260
		return $this->_json($url,$method,$parameters);
261
	}
262
263
	/**
264
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
265
	 * @param string $element
266
	 * @param string $event
267
	 * @param string $url the request address
268
	 * @param string $method default get
269
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
270
	 */
271
	public function jsonOn($event,$element, $url,$method="get",$parameters=array()) {
272
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
273
		return $this->_add_event($element, $this->jsonDeferred($url,$method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
274
	}
275
276
	/**
277
	 * Prepares an ajax request delayed and receives the JSON data types by assigning DOM elements with the same name
278
	 * @param string $url the request url
279
	 * @param string $method Method used
280
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
281
	 */
282
	public function jsonDeferred($url, $method="get", $parameters=[]) {
283
		$parameters["immediatly"]=false;
284
		return $this->_json($url,$method,$parameters);
285
	}
286
287
	/**
288
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name
289
	 * @param string $maskSelector
290
	 * @param string $url the request url
291
	 * @param string $method Method used, default : get
292
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"immediatly"=>false,"rowClass"=>"_json")
293
	 */
294
	private function _jsonArray($maskSelector, $url, $method="get", $parameters=[]) {
295
		$parameters=\array_merge($parameters,["hasLoader"=>false]);
296
		$rowClass=isset($parameters['rowClass']) ? $parameters['rowClass'] : "_json";
297
		$jsCallback=isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
298
		$context=isset($parameters['context']) ? $parameters['context'] : null;
299
		if($context===null){
300
			$parent="$('".$maskSelector."').parent()";
301
			$newElm = "$('#'+newId)";
302
		}else{
303
			$parent=$context;
304
			$newElm = $context.".find('#'+newId)";
305
		}
306
		$appendTo="\t\tnewElm.appendTo(".$parent.");\n";
307
		$retour=$parent.".find('.{$rowClass}').remove();";
308
		$retour.="\tdata=($.isPlainObject(data))?data:JSON.parse(data);\t".$jsCallback.";\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();
309
		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";
310
		$retour.= $appendTo;
311
		$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";
312
		$retour.="\t$(document).trigger('jsonReady',[data]);\n";
313
		$parameters["jsCallback"]=$retour;
314
		return $this->_ajax($method, $url,null,$parameters);
315
	}
316
317
	/**
318
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name
319
	 * @param string $maskSelector
320
	 * @param string $url the request url
321
	 * @param string $method Method used, default : get
322
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"immediatly"=>false,"rowClass"=>"_json")
323
	 */
324
	public function jsonArray($maskSelector, $url, $method="get", $parameters=[]) {
325
		return $this->_jsonArray($maskSelector, $url,$method,$parameters);
326
	}
327
328
	/**
329
	 * 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
330
	 * @param string $maskSelector
331
	 * @param string $url the request url
332
	 * @param string $method Method used, default : get
333
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"rowClass"=>"_json")
334
	 */
335
	public function jsonArrayDeferred($maskSelector, $url, $method="get", $parameters) {
336
		$parameters["immediatly"]=false;
337
		return $this->jsonArray($maskSelector, $url, $method, $parameters);
338
	}
339
340
	/**
341
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name when $event fired on $element
342
	 * @param string $element
343
	 * @param string $event
344
	 * @param string $url the request url
345
	 * @param string $method Method used, default : get
346
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","rowClass"=>"_json","immediatly"=>true)
347
	 */
348
	public function jsonArrayOn($event,$element,$maskSelector, $url,$method="get",$parameters=array()) {
349
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
350
		return $this->_add_event($element, $this->jsonArrayDeferred($maskSelector,$url,$method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
351
	}
352
353
	/**
354
	 * Prepares a Get ajax request
355
	 * To use on an event
356
	 * @param string $url The url of the request
357
	 * @param string $responseElement selector of the HTML element displaying the answer
358
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
359
	 */
360
	public function getDeferred($url, $responseElement="", $parameters=[]) {
361
		$parameters["immediatly"]=false;
362
		return $this->_get($url, $responseElement,$parameters);
363
	}
364
365
	/**
366
	 * Performs a get to $url on the event $event on $element
367
	 * and display it in $responseElement
368
	 * @param string $event
369
	 * @param string $element
370
	 * @param string $url The url of the request
371
	 * @param string $responseElement The selector of the HTML element displaying the answer
372
	 * @param array $parameters 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)
373
	 */
374
	public function getOn($event, $element, $url, $responseElement="", $parameters=array()) {
375
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
376
		return $this->_add_event($element, $this->getDeferred($url,$responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
377
	}
378
379
	/**
380
	 * Performs an ajax request to $url on the event $event on $element
381
	 * and display it in $responseElement
382
	 * @param string $event
383
	 * @param string $element
384
	 * @param string $url The url of the request
385
	 * @param string $responseElement The selector of the HTML element displaying the answer
386
	 * @param array $parameters 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)
387
	 */
388
	public function ajaxOn($event, $element, $url, $responseElement="", $parameters=array()) {
389
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true,"method"=>"get"]);
390
		return $this->_add_event($element, $this->ajaxDeferred($parameters["method"],$url,$responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
391
	}
392
393
	/**
394
	 * Performs a get to $url on the click event on $element
395
	 * and display it in $responseElement
396
	 * @param string $element
397
	 * @param string $url The url of the request
398
	 * @param string $responseElement The selector of the HTML element displaying the answer
399
	 * @param array $parameters 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)
400
	 */
401
	public function ajaxOnClick($element, $url, $responseElement="", $parameters=array()) {
402
		return $this->ajaxOn("click", $element, $url, $responseElement, $parameters);
403
	}
404
405
	/**
406
	 * Performs a get to $url on the click event on $element
407
	 * and display it in $responseElement
408
	 * @param string $element
409
	 * @param string $url The url of the request
410
	 * @param string $responseElement The selector of the HTML element displaying the answer
411
	 * @param array $parameters 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)
412
	 */
413
	public function getOnClick($element, $url, $responseElement="", $parameters=array()) {
414
		return $this->getOn("click", $element, $url, $responseElement, $parameters);
415
	}
416
417
	private function _post($url, $params="{}",$responseElement="", $parameters=[]) {
418
		$parameters["params"]=$params;
419
		return $this->_ajax("POST", $url,$responseElement,$parameters);
420
	}
421
422
	/**
423
	 * Makes an ajax post
424
	 * @param string $url the request url
425
	 * @param string $responseElement selector of the HTML element displaying the answer
426
	 * @param string $params JSON parameters
427
	 * @param array $parameters default : array("jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
428
	 */
429
	public function post($url, $params="{}",$responseElement="", $parameters=[]) {
430
		return $this->_post($url, $params,$responseElement, $parameters);
431
	}
432
433
	/**
434
	 * Prepares a delayed ajax POST
435
	 * to use on an event
436
	 * @param string $url the request url
437
	 * @param string $params JSON parameters
438
	 * @param string $responseElement selector of the HTML element displaying the answer
439
	 * @param array $parameters default : array("jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"immediatly"=>true,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
440
	 */
441
	public function postDeferred($url, $params="{}",$responseElement="", $parameters=[]) {
442
		$parameters["immediatly"]=false;
443
		return $this->_post($url, $params, $responseElement, $parameters);
444
	}
445
446
	/**
447
	 * Performs a post to $url on the event $event fired on $element and pass the parameters $params
448
	 * Display the result in $responseElement
449
	 * @param string $event
450
	 * @param string $element
451
	 * @param string $url The url of the request
452
	 * @param string $params The parameters to send
453
	 * @param string $responseElement selector of the HTML element displaying the answer
454
	 * @param array $parameters 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)
455
	 */
456
	public function postOn($event, $element, $url, $params="{}", $responseElement="", $parameters=array()) {
457
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
458
		return $this->_add_event($element, $this->postDeferred($url, $params, $responseElement, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
459
	}
460
461
	/**
462
	 * Performs a post to $url on the click event fired on $element and pass the parameters $params
463
	 * Display the result in $responseElement
464
	 * @param string $element
465
	 * @param string $url The url of the request
466
	 * @param string $params The parameters to send
467
	 * @param string $responseElement selector of the HTML element displaying the answer
468
	 * @param array $parameters 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)
469
	 */
470
	public function postOnClick($element, $url, $params="{}", $responseElement="", $parameters=array()) {
471
		return $this->postOn("click", $element, $url, $params, $responseElement, $parameters);
472
	}
473
474
	private function _postForm($url, $form, $responseElement, $parameters=[]) {
475
		//$params="{}";$validation=false;$jsCallback=NULL;$attr="id";$hasLoader=true;$ajaxLoader=null;$jqueryDone="html";$ajaxTransition=null;$immediatly=false;$jsCondition=NULL;$headers=NULL;$async=true;
0 ignored issues
show
Unused Code Comprehensibility introduced by
75% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
476
		if(isset($this->params["ajax"])){
477
			extract($this->params["ajax"]);
478
		}
479
		$params="{}";$validation=false;
480
		\extract($parameters);
481
		$async=($async)?"true":"false";
482
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
483
		$retour=$this->_getAjaxUrl($url, $attr);
484
		$retour.="\n$('#".$form."').trigger('ajaxSubmit');";
485
		$retour.="\nvar params=$('#".$form."').serialize();\n";
486
		if(isset($params)){
487
			$retour.="params+='&'+".self::_correctParams($params).";\n";
488
		}
489
		$responseElement=$this->_getResponseElement($responseElement);
490
		$retour.="var self=this;\n";
491
		if($hasLoader===true){
492
			$this->addLoading($retour, $responseElement,$ajaxLoader);
493
		}elseif($hasLoader==="internal"){
494
			$retour.="\n$(this).addClass('loading');";
495
		}
496
		$ajaxParameters=["url"=>"url","method"=>"'POST'","data"=>"params","async"=>$async];
497
		if(isset($headers)){
498
			$ajaxParameters["headers"]=$headers;
499
		}
500
		$this->createAjaxParameters($ajaxParameters, $parameters);
501
		$retour.="$.ajax({".$this->implodeAjaxParameters($ajaxParameters)."}).done(function( data ) {\n";
502
		$retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$ajaxTransition,$jsCallback,$hasLoader)."});\n";
503
504
		if ($validation) {
505
			$retour="$('#".$form."').validate({submitHandler: function(form) {
506
			".$retour."
507
			}});\n";
508
			$retour.="$('#".$form."').submit();\n";
509
		}
510
		$retour=$this->_addJsCondition($jsCondition, $retour);
511
		if ($immediatly)
512
			$this->jquery_code_for_compile[]=$retour;
513
		return $retour;
514
	}
515
516
	/**
517
	 * Performs a post form with ajax
518
	 * @param string $url The url of the request
519
	 * @param string $form The form HTML id
520
	 * @param string $responseElement selector of the HTML element displaying the answer
521
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
522
	 */
523
	public function postForm($url, $form, $responseElement, $parameters=[]) {
524
		$parameters["immediatly"]=true;
525
		return $this->_postForm($url, $form, $responseElement, $parameters);
526
	}
527
528
	/**
529
	 * Performs a delayed post form with ajax
530
	 * For use on an event
531
	 * @param string $url The url of the request
532
	 * @param string $form The form HTML id
533
	 * @param string $responseElement selector of the HTML element displaying the answer
534
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
535
	 */
536
	public function postFormDeferred($url, $form, $responseElement, $parameters=[]) {
537
		$parameters["immediatly"]=false;
538
		return $this->_postForm($url, $form, $responseElement, $parameters);
539
	}
540
541
	/**
542
	 * Performs a post form with ajax in response to an event $event on $element
543
	 * display the result in $responseElement
544
	 * @param string $event
545
	 * @param string $element
546
	 * @param string $url
547
	 * @param string $form
548
	 * @param string $responseElement selector of the HTML element displaying the answer
549
	 * @param array $parameters 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)
550
	 */
551
	public function postFormOn($event, $element, $url, $form, $responseElement="", $parameters=array()) {
552
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
553
		return $this->_add_event($element, $this->postFormDeferred($url, $form, $responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
554
	}
555
556
	/**
557
	 * Performs a post form with ajax in response to the click event on $element
558
	 * display the result in $responseElement
559
	 * @param string $element
560
	 * @param string $url
561
	 * @param string $form
562
	 * @param string $responseElement selector of the HTML element displaying the answer
563
	 * @param array $parameters 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)
564
	 */
565
	public function postFormOnClick($element, $url, $form, $responseElement="", $parameters=array()) {
566
		return $this->postFormOn("click", $element, $url, $form, $responseElement, $parameters);
567
	}
568
}
569