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?