Parcourir la source

added UI::hButtonAjax

Piotr Labudda il y a 9 ans
Parent
commit
7ab1e9fc06
2 fichiers modifiés avec 60 ajouts et 0 suppressions
  1. 58 0
      SE/se-lib/UI.php
  2. 2 0
      SE/se-lib/tmpl/_layout_gora.php

+ 58 - 0
SE/se-lib/UI.php

@@ -316,6 +316,64 @@ class UI {
 		);
 	}
 
+	public static function hButtonAjax($label, $jsEventPrefix, $params = []) {
+		if (!empty($params['data'])) foreach ($params['data'] as $k => $v) $childrens[] = self::h('input', ['type'=>'hidden', 'name'=>$k, 'value'=>$v]);
+		$query = V::get('data', '', $params);
+		return self::h('a', [
+			'class' => V::get('class', 'btn btn-default', $params),
+			'style' => V::get('style', '', $params),
+			'href' => V::get('href', '', $params),
+			'onClick' => "return p5UI__hButtonAjax(this, 'p5UIBtnAjax:{$jsEventPrefix}', '', '" . http_build_query($query) . "')",
+		], $label);
+	}
+	public static function hButtonAjaxOnResponse($jsEventPrefix, $jsCode) {
+		echo self::h('script', [], "
+			jQuery(document).on('p5UIBtnAjax:{$jsEventPrefix}:response', function(e, n, payload) {
+				{$jsCode}
+			})
+		");
+	}
+	public static function hButtonAjaxJsFunction() {
+		echo UI::h('script', [], "
+			function p5UI__hButtonAjax(n, eventNamespace, url, query) {
+			  var dbg = " . ( DBG::isActive() ? 1 : 0 ) . ";
+			  var jqNode = jQuery(n);
+			  var state = {
+			    href: url || n.href,
+			    data: query || ''
+			  }
+			  jQuery(document).trigger('p5UIBtnAjax:' + eventNamespace + ':click', [n, state])
+			  if (jqNode.hasClass('disabled')) { // bootstrap already prevent this action
+			    if (dbg) console.log('WARNING: btn disabled - waiting for response - Cancel?')
+			    return false
+			  }
+			  jqNode.addClass('disabled btn-loading')
+
+			  window.fetch(state.href, {
+			    method: 'POST',
+			    headers: {
+			      'Content-Type': 'application/x-www-form-urlencoded' // query string
+			    },
+			    credentials: 'same-origin',
+			    body: state.data // new URLSearchParams(state.data)
+			  }).then(function(response) {
+			    return response.json()
+			  }).then(function(payload) {
+			    jqNode.removeClass('disabled btn-loading');
+			    jQuery(document).trigger(eventNamespace + ':response', [n, payload]);
+			  }).catch(function(e) {
+			    jQuery(document).trigger(eventNamespace + ':response', [n, 'error' + e]);
+			    jqNode.removeClass('disabled btn-loading');
+			    p5UI__notifyAjaxCallback({
+			      type: 'error',
+			      msg: 'Request error ' + e
+			    });
+			    console.log('loadDataAjax:fetch: ERR:', e);
+			  })
+			  return false;
+			}
+		");
+	}
 	public static function h($tagName, $params = [], $childrens = []) {
 		$emptyTags = [];
 		$emptyTags[] = 'hr';

+ 2 - 0
SE/se-lib/tmpl/_layout_gora.php

@@ -420,6 +420,8 @@ function resetForm(n) {
 }
 	</script>
 
+	<?php UI::hButtonAjaxJsFunction(); ?>
+
 	<style type="text/css">
 .hidden-dbg { display:none; color:silver; }
 .show-hidden-dbg .hidden-dbg { display:inline; }