I am working on a blog application with Codeigniter 3.1.8 and AngularJS v1.7.8.
The Dashboard of the application is "pure" Codeigniter, with Models, Controllers, and views, while the fronted is made up of JSONs managed and displayed by AngularJS.
I have been unable to add post comments from the frontend, via AngularJS.
My AngularJS controller looks like this:
// Post comment
.controller('PostCommentController', ['$scope', '$http', '$routeParams',
function($scope, $http, $routeParams) {
const slug = $routeParams.slug;
$http.get('api/' + slug).then(function(response) {
let post_id = response.data.post.id
$scope.newComment = {
slug: $routeParams.slug,
post_id: post_id,
name: $scope.name,
email: $scope.email,
comment: $scope.comment
};
$scope.createComment = function(){
console.log($scope.newComment);
$http.post('api/comments/create/' + post_id, $scope.newComment);
};
});
}])
My Codeigniter Comments controller (inside the API):
class Comments extends CI_Controller {
public function __construct()
{
parent::__construct();
}
public function create($post_slug){
$data = json_decode(file_get_contents('php://input'), TRUE);
$this->Comments_model->create_comment($post_id);
}
}
In the Comments_model model I have:
public function create_comment($post_id) {
$data = [
'post_id' => $post_id,
'name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'comment' => $this->input->post('comment'),
'aproved' => 0,
'created_at' => date('Y-m-d H:i:s')
];
return $this->db->insert('comments', $data);
}
The line console.log($scope.newComment);
, inside the createComment
function returns an object with all the necessary "details":
{
comment: "Test Angular",
email: "razvan_zamfir80@yahoo.com",
name: "Razvan Zamfir",
post_id: "67",
slug: "who-loves-a-butterfly"
}
Yet, I get a Failed to load resource: the server responded with a status of 500 (Internal Server Error)
error for this url: api/comments/create/67
and the MySQL insert statement looks like this (I acn see it in the browser at the url /api/comments/create/67):
INSERT INTO `comments` (`post_id`, `name`, `email`, `comment`, `aproved`, `created_at`) VALUES (NULL, NULL, NULL, NULL, 0, '2019-10-31 22:06:01')
Where is my mistake?