Completed
Push — master ( 9fed17...55f351 )
by Jean-Christophe
03:12
created

JqueryAjaxTrait::_getOn()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11
Code Lines 10

Duplication

Lines 11
Ratio 100 %

Importance

Changes 0
Metric Value
dl 11
loc 11
rs 9.4285
c 0
b 0
f 0
cc 1
eloc 10
nc 1
nop 6
1
<?php
2
3
namespace Ajax\common\traits;
4
5
use Ajax\service\JString;
6
use Ajax\service\Javascript;
7
use Ajax\service\JQueryAjaxEffect;
8
9
10
/**
11
 * @author jc
12
 * @property array $jquery_code_for_compile
13
 * @property Ajax\JsUtils $jsUtils
14
 * @property array $params
15
 */
16
trait JqueryAjaxTrait {
17
	protected $ajaxDataCall;
18
	protected $ajaxLoader='<span></span><span></span><span></span><span></span><span></span>';
19
20
	abstract public function _add_event($element, $js, $event, $preventDefault=false, $stopPropagation=false,$immediatly=true);
21
	protected function addLoading(&$retour, $responseElement) {
22
		$loading_notifier='<div class="ajax-loader">';
23
		if ($this->ajaxLoader=='') {
24
			$loading_notifier.="Loading...";
25
		} else {
26
			$loading_notifier.=$this->ajaxLoader;
27
		}
28
		$loading_notifier.='</div>';
29
		$retour.="$({$responseElement}).empty();\n";
30
		$retour.="\t\t$({$responseElement}).prepend('{$loading_notifier}');\n";
31
	}
32
33
	public function _get($url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$immediatly=false) {
34
		return $this->_ajax("get", $url,$params,$responseElement,$jsCallback,$attr,$hasLoader,$jqueryDone,$immediatly);
35
	}
36
	public function _post($url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$immediatly=false) {
37
		return $this->_ajax("post", $url,$params,$responseElement,$jsCallback,$attr,$hasLoader,$jqueryDone,$immediatly);
38
	}
39
40
	protected function _ajax($method,$url, $params="{}", $responseElement="", $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$immediatly=false) {
41
		if(JString::isNull($params)){$params="{}";}
42
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
43
		$retour=$this->_getAjaxUrl($url, $attr);
44
		$responseElement=$this->_getResponseElement($responseElement);
45
		$retour.="var self=this;\n";
46
		if($hasLoader===true){
47
			$this->addLoading($retour, $responseElement);
48
		}
49
		$retour.="$.".$method."(url,".$params.").done(function( data ) {\n";
50
		$retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$jsCallback)."});\n";
51
		if ($immediatly)
52
			$this->jquery_code_for_compile[]=$retour;
53
			return $retour;
54
	}
55
56
	protected function setAjaxDataCall(){
57
		$this->ajaxDataCall=function ($responseElement,$jqueryDone="html"){
58
			return JQueryAjaxEffect::{$this->params["ajaxEffect"]}($responseElement,$jqueryDone);
59
		};
60
	}
61
62
	protected function _getAjaxUrl($url,$attr){
63
		$url=$this->_correctAjaxUrl($url);
64
		$retour="url='".$url."';";
65
		$slash="/";
66
		if(JString::endswith($url, "/")===true)
67
			$slash="";
68
		if(JString::isNotNull($attr)){
69
			if ($attr==="value")
70
				$retour.="url=url+'".$slash."'+$(this).val();\n";
71
			elseif ($attr==="html")
72
			$retour.="url=url+'".$slash."'+$(this).html();\n";
73
			elseif($attr!=null && $attr!=="")
74
					$retour.="url=url+'".$slash."'+($(this).attr('".$attr."')||'');\n";
75
		}
76
		return $retour;
77
	}
78
79
	protected function _getOnAjaxDone($responseElement,$jqueryDone,$jsCallback){
80
		$retour="";$call=$this->ajaxDataCall;
81
		if ($responseElement!=="") {
82
			$retour=$call($responseElement,$jqueryDone);
83
		}
84
		$retour.="\t".$jsCallback."\n";
85
		return $retour;
86
	}
87
88
	protected function _getResponseElement($responseElement){
89
		if ($responseElement!=="") {
90
			$responseElement=Javascript::prep_value($responseElement);
91
		}
92
		return $responseElement;
93
	}
94
95
	protected function _correctAjaxUrl($url) {
96
		if ($url!=="/" && JString::endsWith($url, "/")===true)
97
			$url=substr($url, 0, strlen($url)-1);
98
		if (strncmp($url, 'http://', 7)!=0&&strncmp($url, 'https://', 8)!=0) {
99
			$url=$this->jsUtils->getUrl($url);
100
		}
101
		return $url;
102
	}
103
104
	/**
105
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name
106
	 * @param string $url the request address
107
	 * @param string $params Paramètres passés au format JSON
108
	 * @param string $method Method use
109
	 * @param string $jsCallback javascript code to execute after the request
110
	 * @param boolean $immediatly
111
	 */
112
	public function _json($url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context="document",$immediatly=false) {
113
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
114
		$retour=$this->_getAjaxUrl($url, $attr);
115
		$retour.="$.{$method}(url,".$params.").done(function( data ) {\n";
116
		$retour.="\tdata=$.parseJSON(data);for(var key in data){"
117
				."if($('#'+key,".$context.").length){ if($('#'+key,".$context.").is('[value]')) { $('#'+key,".$context.").val(data[key]);} else { $('#'+key,".$context.").html(data[key]); }}};\n";
118
				$retour.="\t".$jsCallback."\n".
119
						"\t$(document).trigger('jsonReady',[data]);\n".
120
						"});\n";
121
				if ($immediatly)
122
					$this->jquery_code_for_compile[]=$retour;
123
					return $retour;
124
	}
125
126
	/**
127
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
128
	 * @param string $element
129
	 * @param string $event
130
	 * @param string $url the request address
131
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get","immediatly"=>true)
132
	 */
133 View Code Duplication
	public function _jsonOn($event,$element, $url,$parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
134
		$preventDefault=true;
135
		$stopPropagation=true;
136
		$jsCallback=null;
137
		$attr="id";
138
		$method="get";
139
		$context="document";
140
		$params="{}";
141
		$immediatly=true;
142
		extract($parameters);
143
		return $this->_add_event($element, $this->_json($url,$method, $params,$jsCallback, $attr,$context), $event, $preventDefault, $stopPropagation,$immediatly);
144
	}
145
146
	/**
147
	 * Makes an ajax request and receives a JSON array data types by copying and assigning them to the DOM elements with the same name
148
	 * @param string $url the request address
149
	 * @param string $params Paramètres passés au format JSON
150
	 * @param string $method Method use
151
	 * @param string $jsCallback javascript code to execute after the request
152
	 * @param string $context jquery DOM element, array container.
153
	 * @param boolean $immediatly
154
	 */
155
	public function _jsonArray($maskSelector, $url, $method="get", $params="{}", $jsCallback=NULL, $attr="id", $context=null,$immediatly=false) {
156
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
157
		$retour=$this->_getAjaxUrl($url, $attr);
158
		if($context===null){
159
			$appendTo="\t\tnewElm.appendTo($('".$maskSelector."').parent());\n";
160
			$newElm = "$('#'+newId)";
161
		}else{
162
			$appendTo="\t\tnewElm.appendTo(".$context.");\n";
163
			$newElm = $context.".find('#'+newId)";
164
		}
165
		$retour.="var self = $(this);\n$.{$method}(url,".$params.").done(function( data ) {\n";
166
		$retour.="\tdata=$.parseJSON(data);$.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();newElm.attr('id',newId);\n";
167
		$retour.= $appendTo;
168
		$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";
169
		$retour.="\t$(document).trigger('jsonReady',[data]);\n";
170
		$retour.="\t".$jsCallback."\n"."});\n";
171
		if ($immediatly)
172
			$this->jquery_code_for_compile[]=$retour;
173
			return $retour;
174
	}
175
	/**
176
	 * Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name when $event fired on $element
177
	 * @param string $element
178
	 * @param string $event
179
	 * @param string $url the request address
180
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","params"=>"{}","method"=>"get", "context"=>null)
181
	 */
182 View Code Duplication
	public function _jsonArrayOn($event,$element, $maskSelector,$url,$parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
183
		$preventDefault=true;
184
		$stopPropagation=true;
185
		$jsCallback=null;
186
		$attr="id";
187
		$method="get";
188
		$context = null;
189
		$params="{}";
190
		$immediatly=true;
191
		extract($parameters);
192
		return $this->_add_event($element, $this->_jsonArray($maskSelector,$url,$method, $params,$jsCallback, $attr, $context), $event, $preventDefault, $stopPropagation,$immediatly);
193
	}
194
195
	public function _postForm($url, $form, $responseElement, $validation=false, $jsCallback=NULL, $attr="id", $hasLoader=true,$jqueryDone="html",$immediatly=false) {
196
		$jsCallback=isset($jsCallback) ? $jsCallback : "";
197
		$retour=$this->_getAjaxUrl($url, $attr);
198
		$retour.="\nvar params=$('#".$form."').serialize();\n";
199
		$responseElement=$this->_getResponseElement($responseElement);
200
		$retour.="var self=this;\n";
201
		if($hasLoader===true){
202
			$this->addLoading($retour, $responseElement);
203
		}
204
		$retour.="$.post(url,params).done(function( data ) {\n";
205
		$retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$jsCallback)."});\n";
206
207
		if ($validation) {
208
			$retour="$('#".$form."').validate({submitHandler: function(form) {
209
			".$retour."
210
			}});\n";
211
			$retour.="$('#".$form."').submit();\n";
212
		}
213
		if ($immediatly)
214
			$this->jquery_code_for_compile[]=$retour;
215
			return $retour;
216
	}
217
218
	/**
219
	 * Effectue un get vers $url sur l'évènement $event de $element en passant les paramètres $params
220
	 * puis affiche le résultat dans $responseElement
221
	 * @param string $element
222
	 * @param string $event
223
	 * @param string $url
224
	 * @param string $params queryString parameters (JSON format). default : {}
225
	 * @param string $responseElement
226
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"jqueryDone"=>"html")
227
	 */
228 View Code Duplication
	public function _getOn($event,$element, $url, $params="{}", $responseElement="", $parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
229
		$preventDefault=true;
230
		$stopPropagation=true;
231
		$jsCallback=null;
232
		$attr="id";
233
		$hasLoader=true;
234
		$immediatly=true;
235
		$jqueryDone="html";
236
		extract($parameters);
237
		return $this->_add_event($element, $this->_get($url, $params, $responseElement, $jsCallback, $attr,$hasLoader,$jqueryDone), $event, $preventDefault, $stopPropagation,$immediatly);
238
	}
239
240
	/**
241
	 * Effectue un post vers $url sur l'évènement $event de $element en passant les paramètres $params
242
	 * puis affiche le résultat dans $responseElement
243
	 * @param string $element
244
	 * @param string $event
245
	 * @param string $url
246
	 * @param string $params queryString parameters (JSON format). default : {}
247
	 * @param string $responseElement
248
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true)
249
	 */
250 View Code Duplication
	public function _postOn($event,$element, $url, $params="{}", $responseElement="", $parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
251
		$preventDefault=true;
252
		$stopPropagation=true;
253
		$jsCallback=null;
254
		$attr="id";
255
		$hasLoader=true;
256
		$immediatly=true;
257
		$jqueryDone="html";
258
		extract($parameters);
259
		return $this->_add_event($element, $this->_post($url, $params, $responseElement, $jsCallback, $attr,$hasLoader,$jqueryDone), $event, $preventDefault, $stopPropagation,$immediatly);
260
	}
261
262
	/**
263
	 * Effectue un post vers $url sur l'évènement $event de $element en passant les paramètres du formulaire $form
264
	 * puis affiche le résultat dans $responseElement
265
	 * @param string $element
266
	 * @param string $event
267
	 * @param string $url
268
	 * @param string $form
269
	 * @param string $responseElement
270
	 * @param array $parameters default : array("preventDefault"=>true,"stopPropagation"=>true,"validation"=>false,"jsCallback"=>NULL,"attr"=>"id","hasLoader"=>true,"immediatly"=>true)
271
	 */
272 View Code Duplication
	public function _postFormOn($event,$element, $url, $form, $responseElement="", $parameters=array()) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
273
		$preventDefault=true;
274
		$stopPropagation=true;
275
		$validation=false;
276
		$jsCallback=null;
277
		$attr="id";
278
		$hasLoader=true;
279
		$immediatly=true;
280
		$jqueryDone="html";
281
		extract($parameters);
282
		return $this->_add_event($element, $this->_postForm($url, $form, $responseElement, $validation, $jsCallback, $attr,$hasLoader,$jqueryDone), $event, $preventDefault, $stopPropagation,$immediatly);
283
	}
284
}