Search code examples
jsonajaxpluginstypo3response

Typo3 v9 - Ajax Plugin JSON response is empty


Having the following TYPO3 Page for ajax request

ajaxAutocomplte_page = PAGE
ajaxAutocomplte_page {
    typeNum = 111871
    10 = COA_INT
    10 {
        userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
        extensionName= MyExt
        pluginName = AjaxAutocomplete
        vendorName = TYPO3
    }

    config {
        disableAllHeaderCode = 1
        additionalHeaders.10.header = Content-type:application/json
        xhtml_cleaning = 0
        debug = 0
        no_cache = 1
        admPanel = 0
    }
}

and returning the following response from Controller

 public function autocompleteJsonAction()
    {
        $query = $_GET['query'];

        $data = $this->templatesRepository->getAutocompleteData($query);

        $this->view->setVariablesToRender(['data']);
        $this->view->assign('data', $data);
    }

will produce JSON data on direct access of URL but not if I request async over javascript

What goes wrong in this case?

enter image description here


Solution

  • Try the below code maybe to help you. It's working for me.

    <?php
    
    public function autocompleteJsonAction() {
        $query = \TYPO3\CMS\Core\Utility\GeneralUtility::_GET('query');
        $data = $this->templatesRepository->getAutocompleteData($query);
    
        $this->response->setHeader('Content-Type', 'application/json', true);
        $this->response->sendHeaders();
    
        $theView = $this->objectManager->get("TYPO3\\CMS\\Extbase\\Mvc\\View\\JsonView");
        $theView->setControllerContext($this->controllerContext);
        $theView->assignMultiple([
            'items' => $data
        ]);
        $theView->setVariablesToRender(['items']);
    
        return $theView->render();
    }
    

    Hope this works for you too!