-1

I could not find information on this particular problem, otherwise than "output has already been sent to the browser" which could be true since I am loading this script while the browser is loaded.

However, the situation:

File is being loaded, Angular http POST is commited, the post then should return a created ID which is then stored into a variable.

Angular:

var res = $http.post('api/letter.php', $scope.letter);
    res.success(function(data, status, headers, config) {
                alert(data);
        $scope.letter.id = data[0].id;
    });
    res.error(function(data, status, headers, config) {
        alert( "failure message: " + JSON.stringify({data: data}));
    }); 

PHP:

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$letter = new Letter();
   if($letter->save())
   {
       echo $letter->id;
   }
}

The output generated in data (Angular) does contain the ID, but also the headers not sent error. Because of that the entire data is stored into the $scope variable, and not just the ID.

How to work around?

UPDATE

Complete error/response: Note the "47" which is the returned ID that is created.

47
( ! ) Warning: Cannot modify header information - headers already sent by (output started at /user/api/letter.php:22) in /user/api/letter.php on line 53

UPDATE

echo json_encode($letter->id); returns the same error.

UPDATE

Error has been found.

In my PHP API Controller I had a structure like:

if(isset($_GET['hello'))
else if(isset($_GET['goodbye'))
else if(isset($_GET['welcome'))

However, by adding an if statement (so no if/else statement) before the first if statement the code decided to print both statements!

Thanks for pointing out the error wasn't in the original POST statement, but another one!

Kraishan
  • 443
  • 5
  • 14
  • 38

1 Answers1

0

This is a very common HTTP error. Check for any echo, print statements before the response is returned and remove them. Echo or print ideally means you are writing something to the browser, which in turn understands that it has received response for its request and blocks all further responses.

Instead return $id as a Json encoded object.

user3227262
  • 563
  • 1
  • 6
  • 16
  • Thanks for your response. However, since I am using multiple AJAX calls output is already given before this HTTP call. I cannot put this call before any other calls because I need AJAX retrieved data. – Kraishan Nov 28 '16 at 14:14
  • Updated the post, returning the json encoded object returns the same error. – Kraishan Nov 28 '16 at 14:18