Skip to content
J-C HERON edited this page Mar 21, 2021 · 12 revisions

Ajax

Ajax integration

An instance of jQuery (phpMv-ui with semantic) is injected by default in the controllers (defined in config.php)

"di"=>[
	"@exec"=>array("jquery"=>function ($controller){
				return \Ubiquity\core\Framework::diSemantic($controller);
			})
],

The $jquery property must be added in the javadoc of a controller to activate the code completion of your IDE on this injection:

 /**
  * @property JsUtils $jquery
  */
class MyController extends ControllerBase{}

Script generation in a view

The view is displayed on the jquery instance, with the renderView method. This allows the compilation of the scripts, and their passage to the view.

	#[Route('_default',name:'home')]
	public function index(){
		$this->jquery->renderView("MyController/index.html");
	}

They are then integrated via the script_foot variable (the Twig raw filter removes the HtmlEntities protection and makes this script executable).

MyController/index.html

{{ script_foot | raw }}

Ajax sample

The getHref method transforms a tags with a data-target attribute into requests performed via ajax. The listenerOn attribute allows all future links in the body of the page to be transformed.

The data-target attribute defines the target of ajax requests. It defines the zone of the page in which the response will be displayed.

public function initialize() {
	parent::initialize();
	$this->jquery->getHref('a[data-target]','',['listenerOn'=>'body']);
}

MyController/index.html

<h1 class="ui inverted header">{{ title }}</h1>
<a class="ui inverted button" href="{{ path('ajax') }}" data-target="#ajax-content">Lien vers ajax</a>
<div class="ui text container" id="ajax-content">

</div>
{{ script_foot|raw }}

Action requested by the ajax link in example:

#[Route('ajax',name:'ajax')]
public function ajax(){
	$datas=['message'=>'This is an ajax message'];
	$this->loadDefaultView($datas);
}

The associated view: MyController/ajax.html

<div class="ui icon inverted message">
    <i class="ui circle info icon"></i>
    {{ message }}
</div>

Clone this wiki locally