HeadersAlreadySentException using AJAX Requests in yii2

Hi guys, following method will throw out error like this:

{"id":23,"id_textbaustein_art":1,"bezeichnung":"Absage - Stelle vergeben (Alternativ-Vorschlag oder Hinweis auf Homepage)","betreff":"Ihre Bewerbung","inhalt":"vielen Dank für Ihre Bewerbung und das uns damit entgegengebrachte Interesse.\r\n\r\nDie Position, auf die Sie sich beworben haben, wurde inzwischen besetzt. \r\n\r\n(Als Alternative können wir momentan folgende Stelle/n anbieten: \r\n\r\nSofern Sie sich für eine der Positionen interessieren, oder Ihre Unterlagen initiativ bei uns belassen möchten, damit wir Sie kontaktieren können, falls erneut eine ähnliche Position vakant wird, geben Sie uns bitte Bescheid.)\r\n\r\nSchauen Sie doch gelegentlich noch einmal auf unsere Homepage. Vielleicht ist unter www.wsl-hannover.de/jobs etwas Passenderes für Sie dabei. \r\n\r\nVielen Dank für Ihr Interesse an einer Vermittlung durch unser Haus!","vermittlung":1,"aktiv":32767,"zuletzt_deaktiviert_am":null,"angelegt_am":"2018-02-13 20:31:38","angelegt_von":null,"aktualisiert_am":"2018-02-13 20:31:38","aktualisiert_von":null,"optimistic_lock":32767}<pre>An Error occurred while handling another error:
yii\web\HeadersAlreadySentException: Headers already sent in /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/frontend/controllers/TextbausteinController.php on line 125. in /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response-&gt;sendHeaders()
#1 /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/vendor/yiisoft/yii2/web/ErrorHandler.php(135): yii\web\Response-&gt;send()
#2 /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/vendor/yiisoft/yii2/base/ErrorHandler.php(111): yii\web\ErrorHandler-&gt;renderException(Object(yii\web\HeadersAlreadySentException))
#3 [internal function]: yii\base\ErrorHandler-&gt;handleException(Object(yii\web\HeadersAlreadySentException))
#4 {main}
Previous exception:
yii\web\HeadersAlreadySentException: Headers already sent in /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/frontend/controllers/TextbausteinController.php on line 125. in /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/vendor/yiisoft/yii2/web/Response.php:366
Stack trace:
#0 /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/vendor/yiisoft/yii2/web/Response.php(339): yii\web\Response-&gt;sendHeaders()
#1 /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/vendor/yiisoft/yii2/base/Application.php(392): yii\web\Response-&gt;send()
#2 /mnt/web421/a2/58/5698458/htdocs/perswitch/test/perswitch_dev/frontend/web/yiic.php(17): yii\base\Application-&gt;run()
#3 {main}</pre>

What does this mean:?? Framework will tell me following, but it doesn’t help avoiding error:
“HeadersAlreadySentException represents an exception caused by any headers that were already sent before web response was sent.”
This is my TextbausteinController.php on line 125:

   public function actionBaustein($textId) {
       $text = Textbaustein::findOne($textId);
       echo Json::encode($text);
   }

Curiously, this error only will be thrown out running code under web server of my hosting provider(Strato). If I use this code under localhost(apache/Linux Mint), everything is all right. What could 'cause this error? I don’t think it’s faulty code, 'cause it runs under localhost. Following code won’t fix problem. It’s ineffective !

public function actionBaustein($textId) {
    $class=new yii\web\HeaderCollection();
    $class->removeAll();
    $text = Textbaustein::findOne($textId);
    echo Json::encode($text);
}

Maybe something like this should work.

$text = Textbaustein::findOne($textId);
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return $text;

You have to return the response, instead of echoing it.

1 Like

don’t echo out your response/json just return it just like @softark pointed out

1 Like

This won’t fix problem. I will get following alert():[object Object] combined with error:
SCRIPT5655: SCRIPT5655: JSON.parse Error: Invalid character at position:2
of following code:

<?=
Dialog::widget();

$script = <<< JS
    $('#bez').change(function(){
        var textId=$(this).val();
        $.get('textbaustein/baustein',{textId:textId},function(data){     
            alert(data);  //Sending debugging info for AJAX error wich will be [object][object] using code of samdark
            var data=$.parseJSON(data);
            $('#IDText').val(data.inhalt);
        });
    });
JS;
$this->registerJS($script);

Furthermore, i intend to get known, why upper error just will be under my hoster, but not under localhost, which also runs with apache web server, Linux OS and php7.2.1

Got it, finally. I had to remove parsing jquery function. Furthermore, i had to pick up element wanted in Controller like this:

public function actionBaustein($textId) {
    $text = Textbaustein::findOne($textId)->inhalt;
    \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    return $text;
}

<?php
$script = <<< JS
    $('#bez').change(function(){
        var textId=$(this).val();
        $.get('textbaustein/baustein',{textId:textId},function(data){
          /*  var data=$.parseJSON(data); // This is not necessary any more... */
            $('#IDText').val(data);
        });
    });
JS;
$this->registerJS($script);
?>
1 Like