Reputation: 39
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
Upvotes: 1
Views: 4873
Reputation: 21
# $result is the whatever you want to output
$response->getBody()->write(json_encode($result));
return $response->withHeader('Content-type', 'application/json');
Upvotes: 0
Reputation: 876
No accepted answer, so for the record from the documentation (Slim 3):
$newResponse = $oldResponse->withHeader('Content-type', 'application/json');
Upvotes: 0
Reputation: 312
You can set the Slim app global content by using this method :
$app->contentType('application/json');
Upvotes: 3
Reputation: 5764
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.
Upvotes: 0