Back to top Back to top
Light Dark

TYPO3 9 frontend use session with eID

html ajax php db

PHP $this->feUserObj

use TYPO3\CMS\Frontend\Utility\EidUtility;

  public function getDateAction(ServerRequestInterface $request): ResponseInterface
	{
		$this->request = $request;

		try {
			$response = new Response();
			$queryParams = $this->request->getQueryParams();

			if($queryParams['eID'] == 'ibox') {
				$action = $queryParams['tx_ibox_eID']['action'];
				if( $action == 'set') {
					$myarr = [
						'title' => 'the name',
						'desc' => 'the description of change'
					];
					$key = 'ibox';
					echo json_encode($this->writeSession($key, $myarr));
					die();
				}

				if( $action == 'del') {
					$key = 'ibox';
					$this->unsetSession($key);
					echo 'is removed';
					die();
				}
			}
			die();

		} catch (\InvalidArgumentException $e) {
			  return (new Response)->withStatus(410);
    } catch (Exception $e) {
        return (new Response)->withStatus(404);
    }
	}

  /**
	 *
	 * @param string $key
	 * @param array $myarr
	 */
    protected function writeSession($key = '',array $myarr = [])
	{

		$this->feUserObj = EidUtility::initFeUser();

		$sessionData = serialize($myarr);
		$this->feUserObj->setKey('ses', $key, $sessionData);
		$this->feUserObj->storeSessionData();

		return $this->feUserObj->getKey('ses', $key);
    }

	/**
	 *
	 * @param string $key
	 */
	protected function unsetSession($key = '')
	{
		$this->feUserObj = EidUtility::initFeUser();
		$this->feUserObj->setKey('ses', $key, NULL);
		$this->feUserObj->storeSessionData();
	}

ext_localconf.php

$GLOBALS['TYPO3_CONF_VARS']['FE']['eID_include']['ibox'] = Xp\Ibox\Utility\Ajax::class . '::getDateAction';

Session.js

(function($){
	$('.session').click(function(){
		$.ajax({
			url: 'index.php',
			data: {
			  'eID':'ibox',
			  'tx_ibox_eID[action]': 'set',
			  'tx_ibox_eID[key]': 1,
			  'tx_ibox_eID[uid]': 17,
			  'tx_ibox_eID[cat]': 2
		   },
		   success: function(e) {
			   console.log(e);
			   $('.status').text('Session: ' + e);
		   }
		});
	});
	// removeSession
	$('.removeSession').click(function(){
		$.ajax({
			url: 'index.php',
			data: {
			  'eID':'ibox',
			  'tx_ibox_eID[action]': 'del'
		   },
		   success: function(e) {
			   console.log(e);
			   $('.status').text('Session: ' + e);
		   }
		});
	});
})(jQuery);

HTML

<div class="status"></div>
<button class="session success button">
  set session
</button>
<br/>
<button class="removeSession alert button">
  remove session
</button>