phpMv  -UI toolkit 2.2.5
jQuery, jQuery UI, Twitter Bootstrap and Semantic-UI library for php & php MVC Frameworks
JsUtilsAjaxTrait.php
Go to the documentation of this file.
1 <?php
2 
3 namespace Ajax\common\traits;
4 
8 
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  abstract public function interval($jsCode,$time,$globalName=null,$immediatly=true);
22 
23  protected function _ajax($method,$url,$responseElement="",$parameters=[]) {
24  if(isset($this->params["ajax"])){
25  extract($this->params["ajax"]);
26  }
27  extract($parameters);
28 
29  $jsCallback=isset($jsCallback) ? $jsCallback : "";
30  $retour=$this->_getAjaxUrl($url, $attr);
31  $originalSelector=$responseElement;
32  $responseElement=$this->_getResponseElement($responseElement);
33  $retour.="var self=this;\n";
34  if($hasLoader===true && JString::isNotNull($responseElement)){
35  $this->addLoading($retour, $responseElement,$ajaxLoader);
36  }elseif($hasLoader==="internal"){
37  $retour.="\n$(this).addClass('loading');";
38  }
39  $ajaxParameters=["url"=>"url","method"=>"'".\strtoupper($method)."'"];
40 
41  $ajaxParameters["async"]=($async?"true":"false");
42 
43  if(isset($params)){
44  $ajaxParameters["data"]=self::_correctParams($params);
45  }
46  if(isset($headers)){
47  $ajaxParameters["headers"]=$headers;
48  }
49  $this->createAjaxParameters($ajaxParameters, $parameters);
50  $retour.="$.ajax({".$this->implodeAjaxParameters($ajaxParameters)."}).done(function( data, textStatus, jqXHR ) {\n";
51  $retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$ajaxTransition,$jsCallback,$hasLoader,($historize?$originalSelector:null))."});\n";
52  $retour=$this->_addJsCondition($jsCondition,$retour);
53  if ($immediatly)
54  $this->jquery_code_for_compile[]=$retour;
55  return $retour;
56  }
57 
58  protected function createAjaxParameters(&$original,$parameters){
59  $validParameters=["dataType"=>"'%value%'","beforeSend"=>"function(jqXHR,settings){%value%}","complete"=>"function(jqXHR){%value%}"];
60  foreach ($validParameters as $param=>$mask){
61  if(isset($parameters[$param])){
62  $original[$param]=\str_replace("%value%", $parameters[$param], $mask);
63  }
64  }
65  }
66 
67  protected function implodeAjaxParameters($ajaxParameters){
68  $s = ''; foreach ($ajaxParameters as $k=>$v) { if ($s !== '') { $s .= ','; } $s .= "'{$k}':{$v}"; }
69  return $s;
70  }
71 
72  protected function _addJsCondition($jsCondition,$jsSource){
73  if(isset($jsCondition)){
74  return "if(".$jsCondition."){\n".$jsSource."\n}";
75  }
76  return $jsSource;
77  }
78 
79 
80  protected function _getAjaxUrl($url,$attr){
81  $url=$this->_correctAjaxUrl($url);
82  $retour="url='".$url."';";
83  $slash="/";
84  if(JString::endswith($url, "/")===true){
85  $slash="";
86  }
87  if(JString::isNotNull($attr)){
88  if ($attr==="value"){
89  $retour.="url=url+'".$slash."'+$(this).val();\n";
90  }elseif ($attr==="html"){
91  $retour.="url=url+'".$slash."'+$(this).html();\n";
92  }elseif(\substr($attr, 0,3)==="js:"){
93  $retour.="url=url+'".$slash."'+".\substr($attr, 3).";\n";
94  }elseif($attr!==null && $attr!=="")
95  $retour.="url=url+'".$slash."'+($(this).attr('".$attr."')||'');\n";
96  }
97  return $retour;
98  }
99 
100  protected function onPopstate(){
101  return "window.onpopstate = function(e){if(e.state){var target=e.state.jqueryDone;$(e.state.selector)[target](e.state.html);}};";
102  }
103 
104  protected function autoActiveLinks($previousURL="window.location.href"){
105  $result= "\nfunction getHref(url) { return \$('a').filter(function(){return \$(this).prop('href') == url; });}";
106  $result.="\nvar myurl={$previousURL};if(window._previousURL) getHref(window._previousURL).removeClass('active');getHref(myurl).addClass('active');window._previousURL=myurl;";
107  return $result;
108  }
109 
110  protected function _getOnAjaxDone($responseElement,$jqueryDone,$ajaxTransition,$jsCallback,$hasLoader=false,$history=null){
111  $retour="";$call=null;
112  if (JString::isNotNull($responseElement)) {
113  if(isset($ajaxTransition)){
114  $call=$this->setAjaxDataCall($ajaxTransition);
115  }elseif(isset($this->ajaxTransition)){
116  $call=$this->ajaxTransition;
117  }
118  if(\is_callable($call))
119  $retour="\t".$call($responseElement,$jqueryDone).";\n";
120  else
121  $retour="\t{$responseElement}.{$jqueryDone}( data );\n";
122  }
123  if(isset($history)){
124  if($this->params["autoActiveLinks"]){
125  $retour.=$this->autoActiveLinks("url");
126  }
127  $retour.="\nwindow.history.pushState({'html':data,'selector':".Javascript::prep_value($history).",'jqueryDone':'{$jqueryDone}'},'', url);";
128  }
129  if($hasLoader==="internal"){
130  $retour.="\n$(self).removeClass('loading');";
131  }
132  $retour.="\t".$jsCallback."\n";
133  return $retour;
134  }
135 
136  protected function _getResponseElement($responseElement){
137  if (JString::isNotNull($responseElement)) {
138  $responseElement=Javascript::prep_jquery_selector($responseElement);
139  }
140  return $responseElement;
141  }
142 
143  protected function _correctAjaxUrl($url) {
144  if ($url!=="/" && JString::endsWith($url, "/")===true)
145  $url=substr($url, 0, strlen($url)-1);
146  if (strncmp($url, 'http://', 7)!=0&&strncmp($url, 'https://', 8)!=0) {
147  $url=$this->getUrl($url);
148  }
149  return $url;
150  }
151 
152  public static function _correctParams($params){
153  if(JString::isNull($params)){
154  return "";
155  }
156  if(\preg_match("@^\{.*?\}$@", $params)){
157  return '$.param('.$params.')';
158  }
159  return $params;
160  }
161 
162  public static function _implodeParams($parameters){
163  $allParameters=[];
164  foreach ($parameters as $params){
165  if(isset($params))
166  $allParameters[]=self::_correctParams($params);
167  }
168  return \implode("+'&'+", $allParameters);
169  }
170 
171  protected function addLoading(&$retour, $responseElement,$ajaxLoader=null) {
172  if(!isset($ajaxLoader)){
174  }
175  $loading_notifier='<div class="ajax-loader">'.$ajaxLoader.'</div>';
176  $retour.="{$responseElement}.empty();\n";
177  $retour.="\t\t{$responseElement}.prepend('{$loading_notifier}');\n";
178  }
179 
180  protected function setAjaxDataCall($params){
181  $result=null;
182  if(!\is_callable($params)){
183  $result=function ($responseElement,$jqueryDone="html") use($params){
184  return AjaxTransition::{$params}($responseElement,$jqueryDone);
185  };
186  }
187  return $result;
188  }
189 
190  protected function setDefaultParameters(&$parameters,$default){
191  foreach ($default as $k=>$v){
192  if(!isset($parameters[$k]))
193  $parameters[$k]=$v;
194  }
195  }
196 
197  public function setAjaxLoader($loader) {
198  $this->ajaxLoader=$loader;
199  }
200 
206  private function _get($url, $responseElement="",$parameters=[]) {
207  return $this->_ajax("get", $url,$responseElement,$parameters);
208  }
209 
216  public function get($url, $responseElement="",$parameters=[]) {
217  $parameters["immediatly"]=true;
218  return $this->_get($url,$responseElement,$parameters);
219  }
220 
228  public function ajax($method,$url, $responseElement="", $parameters=[]) {
229  $parameters["immediatly"]=true;
230  return $this->_ajax($method,$url,$responseElement,$parameters);
231  }
232 
242  public function ajaxInterval($method,$url, $interval,$globalName=null,$responseElement="", $parameters=[]){
243  return $this->interval($this->ajaxDeferred($method, $url,$responseElement,$parameters), $interval,$globalName);
244  }
245 
253  public function ajaxDeferred($method,$url, $responseElement="", $parameters=[]) {
254  $parameters["immediatly"]=false;
255  return $this->_ajax($method,$url,$responseElement,$parameters);
256  }
257 
264  private function _json($url, $method="get",$parameters=[]) {
265  $parameters=\array_merge($parameters,["hasLoader"=>false]);
266  $jsCallback=isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
267  $context=isset($parameters['context']) ? $parameters['context'] : "document";
268  $retour="\tdata=($.isPlainObject(data))?data:JSON.parse(data);\t".$jsCallback.";"
269  ."\n\tfor(var key in data){"
270  ."if($('#'+key,".$context.").length){ if($('#'+key,".$context.").is('[value]')) { $('#'+key,".$context.").val(data[key]);} else { $('#'+key,".$context.").html(data[key]); }}};\n";
271  $retour.="\t$(document).trigger('jsonReady',[data]);\n";
272  $parameters["jsCallback"]=$retour;
273  return $this->_ajax($method, $url,null,$parameters);
274  }
275 
282  public function json($url, $method="get", $parameters=[]) {
283  return $this->_json($url,$method,$parameters);
284  }
285 
294  public function jsonOn($event,$element, $url,$method="get",$parameters=array()) {
295  $this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
296  return $this->_add_event($element, $this->jsonDeferred($url,$method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
297  }
298 
305  public function jsonDeferred($url, $method="get", $parameters=[]) {
306  $parameters["immediatly"]=false;
307  return $this->_json($url,$method,$parameters);
308  }
309 
317  private function _jsonArray($maskSelector, $url, $method="get", $parameters=[]) {
318  $parameters=\array_merge($parameters,["hasLoader"=>false]);
319  $rowClass=isset($parameters['rowClass']) ? $parameters['rowClass'] : "_json";
320  $jsCallback=isset($parameters['jsCallback']) ? $parameters['jsCallback'] : "";
321  $context=isset($parameters['context']) ? $parameters['context'] : null;
322  if($context===null){
323  $parent="$('".$maskSelector."').parent()";
324  $newElm = "$('#'+newId)";
325  }else{
326  $parent=$context;
327  $newElm = $context.".find('#'+newId)";
328  }
329  $appendTo="\t\tnewElm.appendTo(".$parent.");\n";
330  $retour=$parent.".find('.{$rowClass}').remove();";
331  $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();
332  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";
333  $retour.= $appendTo;
334  $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";
335  $retour.="\t$(document).trigger('jsonReady',[data]);\n";
336  $retour.="\t".$jsCallback;
337  $parameters["jsCallback"]=$retour;
338  return $this->_ajax($method, $url,null,$parameters);
339  }
340 
348  public function jsonArray($maskSelector, $url, $method="get", $parameters=[]) {
349  return $this->_jsonArray($maskSelector, $url,$method,$parameters);
350  }
351 
359  public function jsonArrayDeferred($maskSelector, $url, $method="get", $parameters) {
360  $parameters["immediatly"]=false;
361  return $this->jsonArray($maskSelector, $url, $method, $parameters);
362  }
363 
372  public function jsonArrayOn($event,$element,$maskSelector, $url,$method="get",$parameters=array()) {
373  $this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
374  return $this->_add_event($element, $this->jsonArrayDeferred($maskSelector,$url,$method, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
375  }
376 
384  public function getDeferred($url, $responseElement="", $parameters=[]) {
385  $parameters["immediatly"]=false;
386  return $this->_get($url, $responseElement,$parameters);
387  }
388 
398  public function getOn($event, $element, $url, $responseElement="", $parameters=array()) {
399  $this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
400  return $this->_add_event($element, $this->getDeferred($url,$responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
401  }
402 
412  public function ajaxOn($event, $element, $url, $responseElement="", $parameters=array()) {
413  $this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true,"method"=>"get"]);
414  return $this->_add_event($element, $this->ajaxDeferred($parameters["method"],$url,$responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
415  }
416 
425  public function ajaxOnClick($element, $url, $responseElement="", $parameters=array()) {
426  return $this->ajaxOn("click", $element, $url, $responseElement, $parameters);
427  }
428 
437  public function getOnClick($element, $url, $responseElement="", $parameters=array()) {
438  return $this->getOn("click", $element, $url, $responseElement, $parameters);
439  }
440 
448  public function getHref($element,$responseElement="",$parameters=array()){
449  $parameters["attr"]="href";
450  if(JString::isNull($responseElement)){
451  $responseElement='%$(self).attr("data-target")%';
452  }
453  if(!isset($parameters["historize"])){
454  $parameters["historize"]=true;
455  }
456  return $this->getOnClick($element, "",$responseElement,$parameters);
457  }
458 
466  public function postHref($element,$responseElement="",$parameters=array()){
467  $parameters["attr"]="href";
468  if(JString::isNull($responseElement)){
469  $responseElement='%$(this).attr("data-target")%';
470  }
471  if(!isset($parameters["historize"])){
472  $parameters["historize"]=true;
473  }
474  return $this->postOnClick($element, "","{}",$responseElement,$parameters);
475  }
476 
477  private function _post($url, $params="{}",$responseElement="", $parameters=[]) {
478  $parameters["params"]=$params;
479  return $this->_ajax("POST", $url,$responseElement,$parameters);
480  }
481 
489  public function post($url, $params="{}",$responseElement="", $parameters=[]) {
490  return $this->_post($url, $params,$responseElement, $parameters);
491  }
492 
501  public function postDeferred($url, $params="{}",$responseElement="", $parameters=[]) {
502  $parameters["immediatly"]=false;
503  return $this->_post($url, $params, $responseElement, $parameters);
504  }
505 
516  public function postOn($event, $element, $url, $params="{}", $responseElement="", $parameters=array()) {
517  $this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
518  return $this->_add_event($element, $this->postDeferred($url, $params, $responseElement, $parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
519  }
520 
530  public function postOnClick($element, $url, $params="{}", $responseElement="", $parameters=array()) {
531  return $this->postOn("click", $element, $url, $params, $responseElement, $parameters);
532  }
533 
534  private function _postForm($url, $form, $responseElement, $parameters=[]) {
535  if(isset($this->params["ajax"])){
536  extract($this->params["ajax"]);
537  }
538  $params="{}";$validation=false;
539  \extract($parameters);
540  $async=($async)?"true":"false";
541  $jsCallback=isset($jsCallback) ? $jsCallback : "";
542  $retour=$this->_getAjaxUrl($url, $attr);
543  $retour.="\n$('#".$form."').trigger('ajaxSubmit');";
544  $retour.="\nvar params=$('#".$form."').serialize();\n";
545  if(isset($params)){
546  $retour.="params+='&'+".self::_correctParams($params).";\n";
547  }
548  $responseElement=$this->_getResponseElement($responseElement);
549  $retour.="var self=this;\n";
550  if($hasLoader===true){
551  $this->addLoading($retour, $responseElement,$ajaxLoader);
552  }elseif($hasLoader==="internal"){
553  $retour.="\n$(this).addClass('loading');";
554  }
555  $ajaxParameters=["url"=>"url","method"=>"'POST'","data"=>"params","async"=>$async];
556  if(isset($headers)){
557  $ajaxParameters["headers"]=$headers;
558  }
559  $this->createAjaxParameters($ajaxParameters, $parameters);
560  $retour.="$.ajax({".$this->implodeAjaxParameters($ajaxParameters)."}).done(function( data ) {\n";
561  $retour.=$this->_getOnAjaxDone($responseElement, $jqueryDone,$ajaxTransition,$jsCallback,$hasLoader)."});\n";
562 
563  if ($validation) {
564  $retour="$('#".$form."').validate({submitHandler: function(form) {
565  ".$retour."
566  }});\n";
567  $retour.="$('#".$form."').submit();\n";
568  }
569  $retour=$this->_addJsCondition($jsCondition, $retour);
570  if ($immediatly)
571  $this->jquery_code_for_compile[]=$retour;
572  return $retour;
573  }
574 
582  public function postForm($url, $form, $responseElement, $parameters=[]) {
583  $parameters["immediatly"]=true;
584  return $this->_postForm($url, $form, $responseElement, $parameters);
585  }
586 
595  public function postFormDeferred($url, $form, $responseElement, $parameters=[]) {
596  $parameters["immediatly"]=false;
597  return $this->_postForm($url, $form, $responseElement, $parameters);
598  }
599 
610  public function postFormOn($event, $element, $url, $form, $responseElement="", $parameters=array()) {
611  $this->setDefaultParameters($parameters, ["preventDefault"=>true,"stopPropagation"=>true,"immediatly"=>true]);
612  return $this->_add_event($element, $this->postFormDeferred($url, $form, $responseElement,$parameters), $event, $parameters["preventDefault"], $parameters["stopPropagation"],$parameters["immediatly"]);
613  }
614 
624  public function postFormOnClick($element, $url, $form, $responseElement="", $parameters=array()) {
625  return $this->postFormOn("click", $element, $url, $form, $responseElement, $parameters);
626  }
627 }
interval($jsCode, $time, $globalName=null, $immediatly=true)
postDeferred($url, $params="{}", $responseElement="", $parameters=[])
Prepares a delayed ajax POST to use on an event.
_getOnAjaxDone($responseElement, $jqueryDone, $ajaxTransition, $jsCallback, $hasLoader=false, $history=null)
getHref($element, $responseElement="", $parameters=array())
Uses an hyperlink to make an ajax get request.
postHref($element, $responseElement="", $parameters=array())
Uses an hyperlink to make an ajax get request.
ajax($method, $url, $responseElement="", $parameters=[])
Performs an ajax request.
postForm($url, $form, $responseElement, $parameters=[])
Performs a post form with ajax.
postFormOnClick($element, $url, $form, $responseElement="", $parameters=array())
Performs a post form with ajax in response to the click event on $element display the result in $resp...
ajaxInterval($method, $url, $interval, $globalName=null, $responseElement="", $parameters=[])
jsonDeferred($url, $method="get", $parameters=[])
Prepares an ajax request delayed and receives the JSON data types by assigning DOM elements with the ...
static isNotNull($s)
Definition: JString.php:19
_jsonArray($maskSelector, $url, $method="get", $parameters=[])
Performs an ajax request and receives the JSON array data types by assigning DOM elements with the sa...
jsonArray($maskSelector, $url, $method="get", $parameters=[])
Performs an ajax request and receives the JSON array data types by assigning DOM elements with the sa...
_json($url, $method="get", $parameters=[])
Performs an ajax request and receives the JSON data types by assigning DOM elements with the same nam...
post($url, $params="{}", $responseElement="", $parameters=[])
Makes an ajax post.
postOnClick($element, $url, $params="{}", $responseElement="", $parameters=array())
Performs a post to $url on the click event fired on $element and pass the parameters $params Display ...
static endswith($hay, $needle)
Definition: JString.php:12
json($url, $method="get", $parameters=[])
Performs an ajax request and receives the JSON data types by assigning DOM elements with the same nam...
static prep_jquery_selector($value)
Definition: Javascript.php:59
jsonArrayDeferred($maskSelector, $url, $method="get", $parameters)
Peforms an ajax request delayed and receives a JSON array data types by copying and assigning them to...
_add_event($element, $js, $event, $preventDefault=false, $stopPropagation=false, $immediatly=true)
createAjaxParameters(&$original, $parameters)
_addJsCondition($jsCondition, $jsSource)
ajaxOnClick($element, $url, $responseElement="", $parameters=array())
Performs a get to $url on the click event on $element and display it in $responseElement.
jsonOn($event, $element, $url, $method="get", $parameters=array())
Makes an ajax request and receives the JSON data types by assigning DOM elements with the same name w...
getDeferred($url, $responseElement="", $parameters=[])
Prepares a Get ajax request for using on an event.
ajaxDeferred($method, $url, $responseElement="", $parameters=[])
Performs a deferred ajax request.
postOn($event, $element, $url, $params="{}", $responseElement="", $parameters=array())
Performs a post to $url on the event $event fired on $element and pass the parameters $params Display...
static isNull($s)
Definition: JString.php:16
postFormOn($event, $element, $url, $form, $responseElement="", $parameters=array())
Performs a post form with ajax in response to an event $event on $element display the result in $resp...
getOnClick($element, $url, $responseElement="", $parameters=array())
Performs a get to $url on the click event on $element and display it in $responseElement.
setDefaultParameters(&$parameters, $default)
_postForm($url, $form, $responseElement, $parameters=[])
jsonArrayOn($event, $element, $maskSelector, $url, $method="get", $parameters=array())
Performs an ajax request and receives the JSON array data types by assigning DOM elements with the sa...
autoActiveLinks($previousURL="window.location.href")
_ajax($method, $url, $responseElement="", $parameters=[])
addLoading(&$retour, $responseElement, $ajaxLoader=null)
_get($url, $responseElement="", $parameters=[])
Performs an ajax GET request.
ajaxOn($event, $element, $url, $responseElement="", $parameters=array())
Performs an ajax request to $url on the event $event on $element and display it in $responseElement...
_post($url, $params="{}", $responseElement="", $parameters=[])
postFormDeferred($url, $form, $responseElement, $parameters=[])
Performs a delayed post form with ajax For use on an event.
getOn($event, $element, $url, $responseElement="", $parameters=array())
Performs a get to $url on the event $event on $element and display it in $responseElement.