I am making a HTTP request to a url, in which the data is getting post in request headers, but when I am fetching it in controller using the $this->input->post
, it is showing blank.
Angularjs code :
//Code to send email of quiz results
$scope.processresult=function(){
$http({
method:"POST",
url:"http://localhost/quizci/admin/sendresultemail/",
data:{
"riskscore":$scope.datascore
},
})
.success(function (data) {
if (!data.success) {
// if not successful, bind errors to error variables
$scope.errorName = data.errors.name;
$scope.errorSuperhero = data.errors.superheroAlias;
}
else {
// if successful, bind success message to message
$scope.message = data.message;
}
});
}
Controller Function :
function sendresultemail(){
$from_email = "test@test.com";
// $to_email = $this->input->post('email');
$to_email = "abc@gmail.com";
$this->load->model('user_model');
// $result = $this->user_model->get_user_by_id($this->session->userdata($sess_array['id']));
echo "risk score =".$this->input->post('riskscore');
exit;
//Load email library
$this->load->library('email');
$this->email->from($from_email, 'ERMS');
$this->email->to($to_email);
$this->email->subject('Email Test');
$this->email->message($_POST);
//Send mail
if($this->email->send()){
$this->session->set_flashdata("email_sent","Email sent successfully.");
}
else {
$this->session->set_flashdata("email_sent","Error in sending Email.");
$this->load->view('admindash');
}
}
you can see the data in request payload, but in the response it is showing blank
You didn't mention header content type.
$scope.processresult=function(){
$http({
method:"POST",
url:"http://localhost/quizci/admin/sendresultemail/",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data:{
"riskscore":$scope.datascore
},
})
In php.. ex..
public function store()
{
$this->load->database();
$_POST = json_decode(file_get_contents('php://input'), true);
$posts = $this->input->post();
$this->db->insert('posts', $posts);
}
You should return back json in CI not by echo its value.
header('Content-Type: application/json');
echo json_encode( $arr );
In addition, please don't use success in angular since it is deprecate, use then instead.
$http({
method:"POST",
url:"http://localhost/quizci/admin/sendresultemail/",
data:{
"riskscore":$scope.datascore
},
})
.then(function (resp) {
var response = rest.data;
// any code here
});
Sometimes codeigniter fails to get the post data. One solution that worked for me was to set $_POST manually using the following step:
$_POST = json_decode(file_get_contents("php://input"), true);
then run the $this->input->post() function.
Hope that it helps some people.