1

I am fairly new to Slim and so far have had no trouble -- everything has worked as expected, until this issue. I've searched and searched, but I must not be looking in the right place.

I'm using AngularJS with Slim and NotORM. So far I've got user authentication working and I'm working on a simple status update form that saves to a database table - 'post'. The form itself is simple and contains only a textarea element with ng-model set to 'message.text'. When submitted, doPost(message) is called in the controller:

$scope.doPost = function(message) {
        Data.post('message', {
            message: message
        }).then(function(results) {
            Data.toast(results);
            loadRemoteData();
        }, function(error) {
            console.log('message failed to send: ' + error);
        });
        $scope.message = {
            content: ''
        }
    }

My code in the Data service (Data.post('message')) is:

var obj = {};
obj.post = function (q, object) {
    return $http.post(serviceBase + q, object)
    .then(function(results) {
        return results.data;
    },
    function(error) {
        console.log('failed -->' + results.data + '<--');
    });
};
return obj;

And then the PHP:

$app->post('/message', function() use ($app, $db) {
    $response = array();
    $r = json_decode($app->request->getBody());
    $userid = $_SESSION['uid'];
    $displayname = $_SESSION['displayname'];
    verifyRequiredParams(array('text'), $r->message);
    $message = $db->post();
    $data = array(
        'userid' => $uid,
        'displayname' => $displayname,
         'text' => $r->message->text
    );

    $result = $message->insert($data);

    if($result != NULL) {
        $response['status'] = 'success';
        $response['message'] = 'Post successful';
        $response['id'] = $result['id'];
        echoResponse(200, $response);
    } else {
        $response["status"] = "error";
        $response["message"] = "Failed to create message. Please try again";
        echoResponse(200, $response);
    }
});

And in echoResponse():

function echoResponse($status_code, $response) {

    $app = \Slim\Slim::getInstance();

    // Http response code
    $app->status($status_code);

    // setting response content type to json
    $app->contentType('application/json');

    echo json_encode($response);
}

And that's pretty much it to the code. There are no errors, but the message.text does not post to the database and the response returned is empty. I created another form on the page containing an input field of type text and it works fine, using duplicated methods. I have tried everything I could think of and what stands out to me is the Response-Header's Content-Type is somehow text/html instead of application/json (the test form shows json). The table I'm trying to post to looks like this:

CREATE TABLE IF NOT EXISTS `post` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`userid` int(11) NOT NULL,
`displayname` varchar(50) CHARACTER SET utf8,
`text` text CHARACTER SET utf8,
`date` timestamp DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;

Any help would be appreciated. Thanks.

Here are the headers:

Response Headers
Access-Control-Allow-Head... origin, x-requested-with, content-type
Access-Control-Allow-Meth... PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Orig... *
Connection  Keep-Alive
Content-Length  0
Content-Type text/html
Date Fri, 09 Jan 2015 11:52:12 GMT
Keep-Alive timeout=5, max=92
Server Apache/2.2.26 (Unix) DAV/2 PHP/5.4.30 mod_ssl/2.2.26 OpenSSL/0.9.8za
X-Powered-By PHP/5.4.30

Request Headers
Accept application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length 32
Content-Type application/json;charset=utf-8
Cookie PHPSESSID=g9ooedu5kk513pk5f5djug42c4
Host localhost
Referer localhost
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:34.0) Gecko/20100101   Firefox/34.0
user1362339
  • 39
  • 1
  • 3
  • What version of Slim do you use? If you change it to: `header('Content-Type: application/json');` does it work? – Philip Jan 09 '15 at 13:01
  • Also, take a look to the [documentation](http://docs.slimframework.com/#Response-Headers). – Davide Pastore Jan 09 '15 at 21:07
  • @Philip I'm using Slim v2.3.5 - I've tried `header('Content-Type: application/json');` as well as `$app->response()->header('Content-Type', 'application/json');` and each way gives the same result - no error and no response at all. I use Firebug and there is no response tab at all. Which, to me, seems strange since the call doesn't throw an error. Also, as I said there is another 'test' form that I implemented above the problem form on the same page that works fine, while this one gives me the the content type text/html in the response header. @Davide Pastore Thanks. Tried that. – user1362339 Jan 10 '15 at 07:37
  • status and contentType are methods of $app->response, not $app nor $app->response() It's strange you don't see exceptions/errors in the output because of these blatant mistakes. Do you know how to read the php log ? some syntax error in php scripts are logged here. – miellaby Mar 04 '15 at 17:21

4 Answers4

3

You can set the Slim app global content by using this method :

$app->contentType('application/json');
robinef
  • 312
  • 1
  • 7
0

You need to grab the $response because it's a protected object...

$response = $app->response();
$response->header('Content-Type', 'application/json');

$app->render(
  file_get_contents($app->config('templates') . $template), $myPageVars
);

I choose to actually work out the JSON within a template rather than dumping the PHP data directly out. Allows later altering your data feeds without screwing with the data source.

doublejosh
  • 5,548
  • 4
  • 39
  • 45
0

No accepted answer, so for the record from the documentation (Slim 3):

$newResponse = $oldResponse->withHeader('Content-type', 'application/json');
Ryan Brodie
  • 6,554
  • 8
  • 40
  • 57
zak
  • 776
  • 10
  • 10
  • Please format your code. When you edit your post, you will see a nice big yellow block on the right telling you how to do this :) – Frits Jul 20 '16 at 05:00
0
# $result is the whatever you want to output
$response->getBody()->write(json_encode($result));
return $response->withHeader('Content-type', 'application/json');