XF 2.1 [SOLVED] setResponseType() json data not coming through controller reply

asprin

Active member
I've an onchange event handler defined which makes an AJAX call
JavaScript:
// url points to myController/my-method
XF.ajax('GET', url, {'tid':2, 'eid':1}, function (data){
    console.log(data);
});

This is the controller method
PHP:
public function actionMyMethod()
{
    $this->setResponseType('json');

    $tid = $this->filter('tid', 'int');
    $eid = $this->filter('eid', 'int');

    $viewParams = [
        't'  => $tid,
        'e' => $eid
    ];

    return $this->view('AFC:myFunction', '', $viewParams);
}

When the AJAX is complete, the console shows the following:
JavaScript:
{
  "status": "ok",
  "html": {
    "content": ""
  },
  "visitor": {
    "conversations_unread": "0",
    "alerts_unread": "0",
    "total_unread": "0"
  },
  "debug": {
    "time": 0.0758,
    "queries": 3,
    "memory": 6.45
  }
}

I do not see the data passed via the $viewParams array. Also, if I comment out $this->setResponseType('json'); inside my controller, the result console stays the same - as if there is no effect of setting the response type at all.

Any suggestions?
 
Last edited:
Found it. I had to use the following lines:
PHP:
$viewParams = [
   't'  => $tid,
   'e' => $eid
];

$view = $this->view('AFC:myFunction', '', []);
$view->setJsonParams($viewParams);
return $view;
 
Found it. I had to use the following lines:
PHP:
$viewParams = [
   't'  => $tid,
   'e' => $eid
];

$view = $this->view('AFC:myFunction', '', []);
$view->setJsonParams($viewParams);
return $view;
Sorry to bump up an old thread, but this was super helpful!

Curious if this is still the best way to return AJAX responses in 2.2?
 
Back
Top Bottom