XF 2.1 Call an action class through Ajax

abdfahim

Well-known member
I declared a route with Controller = Fahim\TestAddon:MyTestPage and Route prefix = portal-a, where the class looks like below

PHP:
class MyTestPage extends \XF\Pub\Controller\AbstractController
{
    public function actionIndex()
    {
        $params = $this->filter([
            'name' => 'str'
        ]);

        $db = \XF::db();
       
        $results = $db->fetchAllKeyed("SELECT * FROM xf_fahim_test
                                 WHERE `uname` = '".$params['name']."'";

        $viewParams = [
            'data' => $results,
            'params' => $params
        ];


        return $this->view('Fahim\TestAddon:View', 'fahim_portal_a', $viewParams);
    }
}

I have a dropdown in the page where a visitor can select a name, say ABC, and it reloads the page http://example.com/portal-a?name=ABC which fetches correct data for the user ABC using the above controller.

So, that works fine so far.

Now the question is, can I achieve the same without reloading the whole page, e.g., through an Ajax call? I.e., when a visitor chooses a name from the dropdown, it calls the above class through Ajax, return the data to the portal page, and loads the new data in a predefined DIV?

Thanks,
 
Sure you can... I do this in my XenMedio addon.

Just trigger a function on the dropdown change
Code:
    XF.ajax('post', urlTarget), {'name':dropdownSelection}, function(data)
    {
        if (data.html)
        {
            XF.setupHtmlInsert(data.html, $targetDiv);
        }
    });
 
Thanks, but I am getting a 400 bad request.

What I did was

JavaScript:
jQuery.ajax({
    type: "POST",
    url: "{{ link('portal-a/reload') }}",
    dataType:"json",
    success: function(data){
        alert(data);
    },
    error: function(xhr){
        alert("An error occured: " + xhr.status + " " + xhr.statusText);
    }
});

PHP:
class MyTestPage extends \XF\Pub\Controller\AbstractController
{

    public function actionReload()
    {
        $viewParams = [
            'data' => "TEST"
        ];
        $this->setResponseType('json');
        return $this->view('Fahim\TestAddon:View', '', $viewParams);
    }
}

Should I return something else?
 
Last edited:
I solved the JSON issue by creating a custom view class.

However, I am still getting 400 Bad request from Server when I set ajax type = POST. It works perfectly for ajax type = GET.
 
Top Bottom