Using Ajax Output In Widget

I’ve created a widget with (to keep it simple) a link in it. When clicking on this link, an ajax call is made (to the url where the widget is used) and the result of this ajax call will be rendered somewhere else in the widget. Because of reusability i want the ajax call to be handled inside the widget. The problem is, the content of the view, where the widget is called, will always be rendered with it. Is there a good way to render the ajax output “stand-alone”?

My approach:


class MyWidget extends Widget {


    public function run()

    {


        $ajax = $this->_handleAjax();


        if ($ajax) {


           return $ajax;

        

        } else {


            return $this->render('mywidget');


        }


    }


    private function _handleAjax()

    {


        if (Yii::$app->request->getIsAjax() && $_POST['widget-ajax'] == 1) {


            $json['success'] = 1;


            return Json::encode($json);


        }


    }


}

Now, when i’m making an ajax call, the result will be something like this:


<!DOCTYPE html>

  ...

  <h1>My widget:</h1>

  {"success":1}

  ...

</html>

The ajax content will, off course, be rendered in place of the widget, but i want it to be rendered "stand-alone". Is there a way to do this?

renderPartial, renderAjax (there are some differences)

Also if you plan to return json, you can just set response format to ‘json’ and return an array of values:


\Yii::$app->response->format = 'json';

$data = MyModel::find()->asArray()->all();

return $data;

Cool, huh?

Thanks, but both ways still render the ‘main’ view (the view where the widget is called in).

I don’t think the way i want it, is possible at all, since the view where the widget is placed in, will be always rendered (else it can’t call the widget).

Not sure I am helping here… but can you contemplate creating a module for this? All your needs seem straightforward to achieve using some controller action and maybe a reusable module widget for easy access? Module level config can also help you set defaults across your app.