I am creating a loading indicator on my submit button and attaching the \"start\" procedure to the beforeSubmit event using the registerJs function.
It works properly th
So. I have a solution, but it contradicts the documentation...
If you look at the actual redirect function (source):
public function redirect($url, $statusCode = 302, $checkAjax = true)
743 {
744 if (is_array($url) && isset($url[0])) {
745 // ensure the route is absolute
746 $url[0] = '/' . ltrim($url[0], '/');
747 }
748 $url = Url::to($url);
749 if (strpos($url, '/') === 0 && strpos($url, '//') !== 0) {
750 $url = Yii::$app->getRequest()->getHostInfo() . $url;
751 }
752
753 if ($checkAjax) {
754 if (Yii::$app->getRequest()->getIsPjax()) {
755 $this->getHeaders()->set('X-Pjax-Url', $url);
756 } elseif (Yii::$app->getRequest()->getIsAjax()) {
757 $this->getHeaders()->set('X-Redirect', $url);
758 } else {
759 $this->getHeaders()->set('Location', $url);
760 }
761 } else {
762 $this->getHeaders()->set('Location', $url);
763 }
764
765 $this->setStatusCode($statusCode);
766
767 return $this;
768 }
You can see that it checks for Pjax before Ajax and has two different headers as such. the X-Redirect header that is mentioned all over the web and multiple sites, does NOT work for a Pjax call. You must check for X-Pjax-Url for a Pjax call.
I register my own javascript function to handle the redirect like below:
$js = <<< 'SCRIPT'
$(document).on('pjax:complete', function (event, xhr, textStatus, options) {
//$(document).ajaxComplete(function (event, xhr, settings) {
var url = xhr.getResponseHeader('X-Pjax-Url');
if (url) {
window.location = url;
}
});
SCRIPT;
$this->registerJs($js);
And for some reason, this on its own wasn't enough. The source function, by default runs the checkAjax code, but until I explicitly called it from my redirect code, it wouldn't work.
So here is what I use in my controller:
Yii::$app->response->redirect(Yii::getAlias('@web') . '/secure/dashboard/', true)->send();
return;
This has been discussed many, many times and I hope this helps others.