Passed
Push — master ( fc9e05...ccea9a )
by Jean-Christophe
01:46
created

JsUtilsAjaxTrait::postFormDeferred()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 4
dl 0
loc 3
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.="\nfunction getHref(url) { return \$('a').filter(function(){return \$(this).prop('href') == url; });}";
118
			$retour.="\nif(window._previousURL) getHref(window._previousURL).removeClass('active');getHref(url).addClass('active');";
119
			$retour.="\nwindow.history.pushState({'html':data,'selector':".Javascript::prep_value($history).",'jqueryDone':'{$jqueryDone}'},'', url);window._previousURL=url;";
120
		}
121
		if($hasLoader==="internal"){
122
			$retour.="\n$(self).removeClass('loading');";
123
		}
124
		$retour.="\t".$jsCallback."\n";
125
		return $retour;
126
	}
127
128
	protected function _getResponseElement($responseElement){
129
		if (JString::isNotNull($responseElement)) {
130
			$responseElement=Javascript::prep_jquery_selector($responseElement);
131
		}
132
		return $responseElement;
133
	}
134
135
	protected function _correctAjaxUrl($url) {
136
		if ($url!=="/" && JString::endsWith($url, "/")===true)
137
			$url=substr($url, 0, strlen($url)-1);
138
			if (strncmp($url, 'http://', 7)!=0&&strncmp($url, 'https://', 8)!=0) {
139
				$url=$this->getUrl($url);
140
			}
141
			return $url;
142
	}
143
144
	public static function _correctParams($params){
145
		if(JString::isNull($params)){
146
			return "";
147
		}
148
		if(\preg_match("@^\{.*?\}$@", $params)){
149
			return '$.param('.$params.')';
150
		}
151
		return $params;
152
	}
153
154
	public static function _implodeParams($parameters){
155
		$allParameters=[];
156
		foreach ($parameters as $params){
157
			if(isset($params))
158
				$allParameters[]=self::_correctParams($params);
159
		}
160
		return \implode("+'&'+", $allParameters);
161
	}
162
163
	protected function addLoading(&$retour, $responseElement,$ajaxLoader=null) {
164
		if(!isset($ajaxLoader)){
165
			$ajaxLoader=$this->ajaxLoader;
166
		}
167
		$loading_notifier='<div class="ajax-loader">'.$ajaxLoader.'</div>';
168
		$retour.="{$responseElement}.empty();\n";
169
		$retour.="\t\t{$responseElement}.prepend('{$loading_notifier}');\n";
170
	}
171
172
	protected function setAjaxDataCall($params){
173
		$result=null;
174
		if(!\is_callable($params)){
175
			$result=function ($responseElement,$jqueryDone="html") use($params){
176
				return AjaxTransition::{$params}($responseElement,$jqueryDone);
177
			};
178
		}
179
		return $result;
180
	}
181
182
	protected function setDefaultParameters(&$parameters,$default){
183
		foreach ($default as $k=>$v){
184
			if(!isset($parameters[$k]))
185
				$parameters[$k]=$v;
186
		}
187
	}
188
189
	public function setAjaxLoader($loader) {
190
		$this->ajaxLoader=$loader;
191
	}
192
193
	/**
194
	 * Performs an ajax GET request
195
	 * @param string $url The url of the request
196
	 * @param string $responseElement selector of the HTML element displaying the answer
197
	 */
198
	private function _get($url, $responseElement="",$parameters=[]) {
199
		return $this->_ajax("get", $url,$responseElement,$parameters);
200
	}
201
202
	/**
203
	 * Performs an ajax GET request
204
	 * @param string $url The url of the request
205
	 * @param string $responseElement selector of the HTML element displaying the answer
206
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
207
	 */
208
	public function get($url, $responseElement="",$parameters=[]) {
209
		$parameters["immediatly"]=true;
210
		return $this->_get($url,$responseElement,$parameters);
211
	}
212
213
	/**
214
	 * Performs an ajax request
215
	 * @param string $method The http method (get, post, delete, put, head)
216
	 * @param string $url The url of the request
217
	 * @param string $responseElement selector of the HTML element displaying the answer
218
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
219
	 */
220
	public function ajax($method,$url, $responseElement="", $parameters=[]) {
221
		$parameters["immediatly"]=true;
222
		return $this->_ajax($method,$url,$responseElement,$parameters);
223
	}
224
225
	/**
226
	 * Performs a deferred ajax request
227
	 * @param string $method The http method (get, post, delete, put, head)
228
	 * @param string $url The url of the request
229
	 * @param string $responseElement selector of the HTML element displaying the answer
230
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
231
	 */
232
	public function ajaxDeferred($method,$url, $responseElement="", $parameters=[]) {
233
		$parameters["immediatly"]=false;
234
		return $this->_ajax($method,$url,$responseElement,$parameters);
235
	}
236
237
	/**
238
	 * Performs an ajax request and receives the JSON data types by assigning DOM elements with the same name
239
	 * @param string $url the request url
240
	 * @param string $method Method used
241
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
242
	 */
243
	private function _json($url, $method="get",$parameters=[]) {
244
		$parameters=\array_merge($parameters,["hasLoader"=>false]);
245
		$jsCallback=isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
246
		$context=isset($parameters['context']) ? $parameters['context'] : "document";
247
		$retour="\tdata=($.isPlainObject(data))?data:JSON.parse(data);\t".$jsCallback.";\n\tfor(var key in data){"
248
				."if($('#'+key,".$context.").length){ if($('#'+key,".$context.").is('[value]')) { $('#'+key,".$context.").val(data[key]);} else { $('#'+key,".$context.").html(data[key]); }}};\n";
249
				$retour.="\t$(document).trigger('jsonReady',[data]);\n";
250
		$parameters["jsCallback"]=$retour;
251
		return $this->_ajax($method, $url,null,$parameters);
252
	}
253
254
	/**
255
	 * Performs an ajax request and receives the JSON data types by assigning DOM elements with the same name
256
	 * @param string $url the request url
257
	 * @param string $method Method used
258
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
259
	 */
260
	public function json($url, $method="get", $parameters=[]) {
261
		return $this->_json($url,$method,$parameters);
262
	}
263
264
	/**
265
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
266
	 * @param string $element
267
	 * @param string $event
268
	 * @param string $url the request address
269
	 * @param string $method default get
270
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
271
	 */
272
	public function jsonOn($event,$element, $url,$method="get",$parameters=array()) {
273
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
274
		return $this->_add_event($element, $this->jsonDeferred($url,$method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
275
	}
276
277
	/**
278
	 * Prepares an ajax request delayed and receives the JSON data types by assigning DOM elements with the same name
279
	 * @param string $url the request url
280
	 * @param string $method Method used
281
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>"document","jsCondition"=>NULL,"headers"=>null,"immediatly"=>false)
282
	 */
283
	public function jsonDeferred($url, $method="get", $parameters=[]) {
284
		$parameters["immediatly"]=false;
285
		return $this->_json($url,$method,$parameters);
286
	}
287
288
	/**
289
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name
290
	 * @param string $maskSelector
291
	 * @param string $url the request url
292
	 * @param string $method Method used, default : get
293
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"immediatly"=>false,"rowClass"=>"_json")
294
	 */
295
	private function _jsonArray($maskSelector, $url, $method="get", $parameters=[]) {
296
		$parameters=\array_merge($parameters,["hasLoader"=>false]);
297
		$rowClass=isset($parameters['rowClass']) ? $parameters['rowClass'] : "_json";
298
		$jsCallback=isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
299
		$context=isset($parameters['context']) ? $parameters['context'] : null;
300
		if($context===null){
301
			$parent="$('".$maskSelector."').parent()";
302
			$newElm = "$('#'+newId)";
303
		}else{
304
			$parent=$context;
305
			$newElm = $context.".find('#'+newId)";
306
		}
307
		$appendTo="\t\tnewElm.appendTo(".$parent.");\n";
308
		$retour=$parent.".find('.{$rowClass}').remove();";
309
		$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();
310
		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";
311
		$retour.= $appendTo;
312
		$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";
313
		$retour.="\t$(document).trigger('jsonReady',[data]);\n";
314
		$parameters["jsCallback"]=$retour;
315
		return $this->_ajax($method, $url,null,$parameters);
316
	}
317
318
	/**
319
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name
320
	 * @param string $maskSelector
321
	 * @param string $url the request url
322
	 * @param string $method Method used, default : get
323
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"immediatly"=>false,"rowClass"=>"_json")
324
	 */
325
	public function jsonArray($maskSelector, $url, $method="get", $parameters=[]) {
326
		return $this->_jsonArray($maskSelector, $url,$method,$parameters);
327
	}
328
329
	/**
330
	 * 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
331
	 * @param string $maskSelector
332
	 * @param string $url the request url
333
	 * @param string $method Method used, default : get
334
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","context"=>null,"jsCondition"=>NULL,"headers"=>null,"rowClass"=>"_json")
335
	 */
336
	public function jsonArrayDeferred($maskSelector, $url, $method="get", $parameters) {
337
		$parameters["immediatly"]=false;
338
		return $this->jsonArray($maskSelector, $url, $method, $parameters);
339
	}
340
341
	/**
342
	 * Performs an ajax request and receives the JSON array data types by assigning DOM elements with the same name when $event fired on $element
343
	 * @param string $element
344
	 * @param string $event
345
	 * @param string $url the request url
346
	 * @param string $method Method used, default : get
347
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","rowClass"=>"_json","immediatly"=>true)
348
	 */
349
	public function jsonArrayOn($event,$element,$maskSelector, $url,$method="get",$parameters=array()) {
350
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
351
		return $this->_add_event($element, $this->jsonArrayDeferred($maskSelector,$url,$method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
352
	}
353
354
	/**
355
	 * Prepares a Get ajax request
356
	 * for using on an event
357
	 * @param string $url The url of the request
358
	 * @param string $responseElement selector of the HTML element displaying the answer
359
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
360
	 */
361
	public function getDeferred($url, $responseElement="", $parameters=[]) {
362
		$parameters["immediatly"]=false;
363
		return $this->_get($url, $responseElement,$parameters);
364
	}
365
366
	/**
367
	 * Performs a get to $url on the event $event on $element
368
	 * and display it in $responseElement
369
	 * @param string $event the event 
370
	 * @param string $element the element on which event is observed
371
	 * @param string $url The url of the request
372
	 * @param string $responseElement The selector of the HTML element displaying the answer
373
	 * @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)
374
	 */
375
	public function getOn($event, $element, $url, $responseElement="", $parameters=array()) {
376
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
377
		return $this->_add_event($element, $this->getDeferred($url,$responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
378
	}
379
380
	/**
381
	 * Performs an ajax request to $url on the event $event on $element
382
	 * and display it in $responseElement
383
	 * @param string $event the event observed
384
	 * @param string $element the element on which event is observed
385
	 * @param string $url The url of the request
386
	 * @param string $responseElement The selector of the HTML element displaying the answer
387
	 * @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)
388
	 */
389
	public function ajaxOn($event, $element, $url, $responseElement="", $parameters=array()) {
390
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true,"method"=>"get"]);
391
		return $this->_add_event($element, $this->ajaxDeferred($parameters["method"],$url,$responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
392
	}
393
394
	/**
395
	 * Performs a get to $url on the click event on $element
396
	 * and display it in $responseElement
397
	 * @param string $element the element on which event is observed
398
	 * @param string $url The url of the request
399
	 * @param string $responseElement The selector of the HTML element displaying the answer
400
	 * @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)
401
	 */
402
	public function ajaxOnClick($element, $url, $responseElement="", $parameters=array()) {
403
		return $this->ajaxOn("click", $element, $url, $responseElement, $parameters);
404
	}
405
406
	/**
407
	 * Performs a get to $url on the click event on $element
408
	 * and display it in $responseElement
409
	 * @param string $element the element on which click is observed
410
	 * @param string $url The url of the request
411
	 * @param string $responseElement The selector of the HTML element displaying the answer
412
	 * @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)
413
	 */
414
	public function getOnClick($element, $url, $responseElement="", $parameters=array()) {
415
		return $this->getOn("click", $element, $url, $responseElement, $parameters);
416
	}
417
	
418
	/**
419
	 * Uses an hyperlink to make an ajax get request
420
	 * @param string $element an hyperlink selector
421
	 * @param string $responseElement the target of the ajax request (data-target attribute of the element is used if responseElement is omited)
422
	 * @param array $parameters 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)
423
	 * @return $this
424
	 */
425
	public function getHref($element,$responseElement="",$parameters=array()){
426
		$parameters["attr"]="href";
427
		if(JString::isNull($responseElement)){
428
			$responseElement='%$(self).attr("data-target")%';
429
		}
430
		if(!isset($parameters["historize"])){
431
			$parameters["historize"]=true;
432
		}
433
		return $this->getOnClick($element, "",$responseElement,$parameters);
434
	}
435
	
436
	/**
437
	 * Uses an hyperlink to make an ajax get request
438
	 * @param string $element an hyperlink selector
439
	 * @param string $responseElement the target of the ajax request (data-target attribute of the element is used if responseElement is omited)
440
	 * @param array $parameters 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)
441
	 * @return $this
442
	 */
443
	public function postHref($element,$responseElement="",$parameters=array()){
444
		$parameters["attr"]="href";
445
		if(JString::isNull($responseElement)){
446
			$responseElement='%$(this).attr("data-target")%';
447
		}
448
		if(!isset($parameters["historize"])){
449
			$parameters["historize"]=true;
450
		}
451
		return $this->postOnClick($element, "","{}",$responseElement,$parameters);
452
	}
453
454
	private function _post($url, $params="{}",$responseElement="", $parameters=[]) {
455
		$parameters["params"]=$params;
456
		return $this->_ajax("POST", $url,$responseElement,$parameters);
457
	}
458
459
	/**
460
	 * Makes an ajax post
461
	 * @param string $url the request url
462
	 * @param string $responseElement selector of the HTML element displaying the answer
463
	 * @param string $params JSON parameters
464
	 * @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)
465
	 */
466
	public function post($url, $params="{}",$responseElement="", $parameters=[]) {
467
		return $this->_post($url, $params,$responseElement, $parameters);
468
	}
469
470
	/**
471
	 * Prepares a delayed ajax POST
472
	 * to use on an event
473
	 * @param string $url the request url
474
	 * @param string $params JSON parameters
475
	 * @param string $responseElement selector of the HTML element displaying the answer
476
	 * @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)
477
	 */
478
	public function postDeferred($url, $params="{}",$responseElement="", $parameters=[]) {
479
		$parameters["immediatly"]=false;
480
		return $this->_post($url, $params, $responseElement, $parameters);
481
	}
482
483
	/**
484
	 * Performs a post to $url on the event $event fired on $element and pass the parameters $params
485
	 * Display the result in $responseElement
486
	 * @param string $event
487
	 * @param string $element
488
	 * @param string $url The url of the request
489
	 * @param string $params The parameters to send
490
	 * @param string $responseElement selector of the HTML element displaying the answer
491
	 * @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)
492
	 */
493
	public function postOn($event, $element, $url, $params="{}", $responseElement="", $parameters=array()) {
494
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
495
		return $this->_add_event($element, $this->postDeferred($url, $params, $responseElement, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
496
	}
497
498
	/**
499
	 * Performs a post to $url on the click event fired on $element and pass the parameters $params
500
	 * Display the result in $responseElement
501
	 * @param string $element
502
	 * @param string $url The url of the request
503
	 * @param string $params The parameters to send
504
	 * @param string $responseElement selector of the HTML element displaying the answer
505
	 * @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)
506
	 */
507
	public function postOnClick($element, $url, $params="{}", $responseElement="", $parameters=array()) {
508
		return $this->postOn("click", $element, $url, $params, $responseElement, $parameters);
509
	}
510
511
	private function _postForm($url, $form, $responseElement, $parameters=[]) {
512
		if(isset($this->params["ajax"])){
513
			extract($this->params["ajax"]);
514
		}
515
		$params="{}";$validation=false;
516
		\extract($parameters);
517
		$async=($async)?"true":"false";
518
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
519
		$retour=$this->_getAjaxUrl($url, $attr);
520
		$retour.="\n$('#".$form."').trigger('ajaxSubmit');";
521
		$retour.="\nvar params=$('#".$form."').serialize();\n";
522
		if(isset($params)){
523
			$retour.="params+='&'+".self::_correctParams($params).";\n";
524
		}
525
		$responseElement=$this->_getResponseElement($responseElement);
526
		$retour.="var self=this;\n";
527
		if($hasLoader===true){
528
			$this->addLoading($retour, $responseElement,$ajaxLoader);
529
		}elseif($hasLoader==="internal"){
530
			$retour.="\n$(this).addClass('loading');";
531
		}
532
		$ajaxParameters=["url"=>"url","method"=>"'POST'","data"=>"params","async"=>$async];
533
		if(isset($headers)){
534
			$ajaxParameters["headers"]=$headers;
535
		}
536
		$this->createAjaxParameters($ajaxParameters, $parameters);
537
		$retour.="$.ajax({".$this->implodeAjaxParameters($ajaxParameters)."}).done(function( data ) {\n";
538
		$retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$ajaxTransition,$jsCallback,$hasLoader)."});\n";
539
540
		if ($validation) {
541
			$retour="$('#".$form."').validate({submitHandler: function(form) {
542
			".$retour."
543
			}});\n";
544
			$retour.="$('#".$form."').submit();\n";
545
		}
546
		$retour=$this->_addJsCondition($jsCondition, $retour);
547
		if ($immediatly)
548
			$this->jquery_code_for_compile[]=$retour;
549
		return $retour;
550
	}
551
552
	/**
553
	 * Performs a post form with ajax
554
	 * @param string $url The url of the request
555
	 * @param string $form The form HTML id
556
	 * @param string $responseElement selector of the HTML element displaying the answer
557
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
558
	 */
559
	public function postForm($url, $form, $responseElement, $parameters=[]) {
560
		$parameters["immediatly"]=true;
561
		return $this->_postForm($url, $form, $responseElement, $parameters);
562
	}
563
564
	/**
565
	 * Performs a delayed post form with ajax
566
	 * For use on an event
567
	 * @param string $url The url of the request
568
	 * @param string $form The form HTML id
569
	 * @param string $responseElement selector of the HTML element displaying the answer
570
	 * @param array $parameters default : array("params"=>"{}","jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"ajaxLoader"=>null,"jqueryDone"=>"html","ajaxTransition"=>null,"jsCondition"=>NULL,"headers"=>null,"historize"=>false)
571
	 */
572
	public function postFormDeferred($url, $form, $responseElement, $parameters=[]) {
573
		$parameters["immediatly"]=false;
574
		return $this->_postForm($url, $form, $responseElement, $parameters);
575
	}
576
577
	/**
578
	 * Performs a post form with ajax in response to an event $event on $element
579
	 * display the result in $responseElement
580
	 * @param string $event
581
	 * @param string $element
582
	 * @param string $url
583
	 * @param string $form
584
	 * @param string $responseElement selector of the HTML element displaying the answer
585
	 * @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)
586
	 */
587
	public function postFormOn($event, $element, $url, $form, $responseElement="", $parameters=array()) {
588
		$this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
589
		return $this->_add_event($element, $this->postFormDeferred($url, $form, $responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
590
	}
591
592
	/**
593
	 * Performs a post form with ajax in response to the click event on $element
594
	 * display the result in $responseElement
595
	 * @param string $element
596
	 * @param string $url
597
	 * @param string $form
598
	 * @param string $responseElement selector of the HTML element displaying the answer
599
	 * @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)
600
	 */
601
	public function postFormOnClick($element, $url, $form, $responseElement="", $parameters=array()) {
602
		return $this->postFormOn("click", $element, $url, $form, $responseElement, $parameters);
603
	}
604
}
605