I've built CRUD application using Codeigniter + AngularJS
how to post data in code-igniter controller
I am using this function get all POST data
$data = json_decode($this->input->raw_input_stream , TRUE);
But I want specific value using this function but response is NULL
$x = $this->input->input_stream('email', TRUE);
and one more question is how to apply code-igniter form validation
for this $data
Thank You
Please help me
Try following way.
I've assumed your code and provided an example, do the necessary changes as per your need.
Angular Js
console.log("posting data....");
$http({
method: 'POST',
url: '<?php echo base_url(); ?>user/add',
headers: {'Content-Type': 'application/json'},
data: JSON.stringify({name: $scope.name,city:$scope.city})
}).success(function (data) {
console.log(data);
$scope.message = data.status;
});
Controller action
public function add()
{
// Here you will get data from angular ajax request in json format so you have to decode that json data you will get object array in $request variable
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$name = $request->name;
$city = $request->city;
$id = $this->user_model->AddUser($name,$city);
if($id)
{
echo $result = '{"status" : "success"}';
}else{
echo $result = '{"status" : "failure"}';
}
}
Related
I have a problem with transferring data to the database.
So yes - I created a controller in CodeIgniter 3, which is to send data to the database.
Before sending, the data is checked using JWT.
My code PHP looks like this:
public function create()
{
$token = $this->input->post('token');
$this->jwt->decode($token, config_item('encryption_key'));
$payload = $this->input->post('payload');
unset($payload['login']);
unset($payload['email']);
unset($payload['role']);
$note = $this->input->post('note');
$note = json_encode($note);
$data = $payload;
$data['note'] = $note;
$this->notes_model->create($data);
}
AngularJS:
$scope.noteCreated = function( note ){
$http({
method: 'POST', url: 'api/admin/notes/create/', data: {'note' : note, token: checkToken.raw(), payload: checkToken.payload()} }
).then(function (){
$scope.success = true;
$timeout( function(){
$scope.success = false;
$scope.note = {};
console.log(note);
}, 2000);
},function (error){
console.log('Blad we wczytywaniu danych');
});
}
The data it receives after sending it is in this form:
And they should look like this:
Problem: How to transfer data to get to your columns?
To save data into different columns, you have to make array like this:
$data['noted'] = $note['noted'];
$data['id_domain_rel'] = $note['id_domain_rel'];
now you can pass $data .
Please dont use json_encode.
I'm using an API to send sms in my codeigniter project. After sending, it will return a response array in the form of json to a callback url in my project. And i need to update this response in my database. Here is my code :
the response array will be similar as follows :
{"req_id":"809ff62f-74a9-45a5-9cb5-5e60763289af","status":"0" ,"comment":"OK"}
my callback url redirects to following function in my controller
public function templateCallback() {
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, TRUE);
$reqID = $obj->req_id;
$status = $obj->status;
print_r($obj);
$this->db->where('TemplateRequestID', $reqID);
$this->db->set('TemplateApproved', $status);
$this->db->update('templatemaster_tbl');
}
But its never get updated. What is wrong in my code ? I'm not good in json. So i'm not sure is this the correct way to fetch and decode json array in php. Someone please help me.
To test this i have created a view in my project and send this same array through an ajax function like :
var base_url = '<?php echo base_url()?>';
$('#test').click(function() {
var val = $('#testvalue').text();
$.ajax({
type: 'post',
url: base_url + 'API/templateCallback',
data: {
val
},
success: function (response) { console.log(response);
}
});
});
and try to print both $json and $obj in controller function.
$json displays a string like : val=%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D
and $obj displays nothing
If your $json contains encoded value (%7B%22req_id%22%3A%228b3eef97-330a-4271-8450-0676fbac8885%22%2C%22status%22%3A%220%22%2C%22comment%22%3A%22OK%22%7D) you should decode it first with urldecode.
So proper code would be:
...
$jsonEncoded = file_get_contents('php://input');
$json = urldecode($jsonEncoded);
$obj = json_decode($json, TRUE);
...
I am new to angular.So i dont know i am doing it in the right way.I am working in codeigniter along with angular.I need to get the id which i was passing though the angular $http service in my codeigniter controller.. I didn't get any console errors. Simply the data is not returning.. This is my angular controller
app.controller("newsController_id",function($scope,$http,$routeParams){
$http({ method:'POST',
url:'Controller1/get_list_id',
params:{id:$routeParams.id}
})
.then(function (response) {
$scope.blogs_id = response.data;
})
codeigniter controller
public function get_list_id() {
$id=$this->input->post('id');
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
There are no errors in the codeigniter model and view pages..since i got my result perfectly when i hardcoded the id value as 6.But no output when i posting the id.help me solving this
you are doing wrong way to pass data angujarjs to codeigniter.
if you want to pass data in POST method pass object in $http service on data section like below
AngularJS Code
$http({
method:'post',
url:'/login',
dataType:"json",
data:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
Codeigniter Code
$vEmail = $this->input->post('vEmail');
$vPassword = $this->input->post('vPassword');
If you want to pass data usgin GET you should be pass data in Param section like below
$http({
method:'get',
url:'/login',
dataType:"json",
params:{"vEmail":$scope.vEmail,"vPassword":$scope.vPassword},
}).then(function(suc){
console.log(suc);
},function(err){
console.log(err);
});
you can get that in codeigniter using get method like below
$this->input->get('vEmail');
You can not get the data by $_POST or $this->input->post , You should have something like this in constructor:
$postdata = file_get_contents("php://input");
$this->request = json_decode($postdata);
Now In controller, you can access the id:
$id = $this->request->id;
But it has a problem, you can't use Codeigniter form validation, because it works with $_POST superglobal. You can do something like this instead (in constructor):
$objectRequest = json_decode( file_get_contents("php://input") );
$this->request = xss_clean( json_decode(json_encode($objectRequest), true) );
$_POST = $this->request;
But this time you can access to id by the following example:
$id = $this->request['id'];
in order to get the post variables from angular you need use the following code
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
instead of $id=$this->input->post('id');
so your $id = $myData->id;
Your final code would look like this:
public function get_list_id() {
$postdata = file_get_contents("php://input");
$myData = json_decode($postdata);
$id = $myData->id;
//$id='6';
$data = $this->Blog_model->getAll_id($id);
$this->output->set_content_type('application/json')->set_output(json_encode($data));
}
Ajax call is made in the background
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
var data = {elementID: value};
var json = JSON.stringify(data);
$.ajax({
url: 'php/validator_signup.php',
dataType: 'json',
type: 'post',
data: json,
success: function(data){
var parsedResponse = JSON.parse(data);
console.log(parsedResponse);
/*
if(data.response === 1){
$('#'+elementID+'-status').css("background-image", "url(img/signup/no.png)");
}else if(data.response === 0){
$('#'+elementID+'-status').css("background-image", "url(img/signup/yes.png)"); }
*/
}
});
}
}
validator_signup.php received the call. So far in test mode PHP will receive the string, parse it and encode again to return to JS:
$post = $_POST['data'];
$data = json_decode($post, true); //decode as associative array
$details = $data[0];
echo json_encode($details);
JS then needs to print this in console.
I get this:
null
instead of the value which I expect back.
Result is same whether I parse returned data or not.
If I understand it correctly, the problem is on PHP side?
There does not appear to be any value in converting to json when your data is so simple, you can just use a regular js object that jquery will convert to form data.
Also, as both the key and value you send are unknown, i would suggest sending the data in a different structure so its easy to retrieve:
var signupValidate = function(elementID){
var value = $('#' + elementID).val();
if (value !== ''){
$('#'+elementID+'-status').css("background-image", "url(img/signup/spinner.gif)");
$.ajax({
url: 'php/validator_signup.php',
type: 'post',
// ▼key ▼value ▼key ▼value
data: { id: elementID, val: value},
success: function(response){
console.log(response.message);
}
});
}
}
In php you can access the data via $_POST, and as you know the keys, its simple:
<?php
$id = $_POST['id'];
$val = $_POST['val'];
//set correct header, jquery will parse the json for you
header('Content-Type: application/json');
echo json_encode([
'message'=>'Request received with the id of: ' . $id . 'and the value of: ' . $val,
]);
die();
Change:
data: json,
To:
data: { data: json},
This is because you aren't giving the sent data a POST parameter to then be used server side to retrieve it.
Then, you can simply fetch the code server-side like this:
$data = json_decode($_POST['data']);
Hope this helps!
Here, since you are checking whether data is being post, if you see in Network, no data is being posted. To fix it, change this part:
var data = {elementID: value};
To this:
var data = {data: {elementID: value}};
Consider removing conversion of Data
PHP automatically handles the $_POST as an array! So you don't need to use the reconversion. Please eliminate this part:
var json = JSON.stringify(data); // Remove this.
And in the server side:
$data = json_decode($post, true); // Remove this
$data = $_POST['data']; // Change this
Update
OP said data[elementID]:gh is sent to the PHP file.
If this is the case, then if the data needs to be "gh" in JSON, then:
$res = $_POST["elementID"];
die(json_encode(array("response" => $res)));
This will send:
{
"response": "gh"
}
And in the client side, you don't need anything other than this:
$.post('php/validator_signup.php', function (data) {
var parsedResponse = JSON.parse(data);
console.log(data);
});
JSON data is sent to the server as a raw http input it is not associated with query name like $_POST['data'] or anything like that which means you must access the input string not a data post value to do so you need to use
$rawInput = json_decode(file_get_contents('php://input'), true);
$elementValue = $rawInput['elementId'];
thats it
$_POST = json_decode(file_get_contents('php://input'), true);
$data = $_POST['data'];
I have being battling almost for day now about something that sound quite simple. I'm trying to pass an object using angular post ajax. I'm using PHP with codeigniter framework and I'm not getting any values pass. there have to be something wrong with the way I'm sending the object in angular because php is not getting anything. It's going to the right place because I'm getting a respond error saying "Trying to get property of non-object, line 173" line 173 is $AccessKey = $data->AccessKey;
this is my angular code
app.controller('loginController', function($scope, $http){
//$scope.formData = {};
$scope.processForm = function(){
$http({
method : 'POST',
url : 'http://localhost:8888/employees/login',
data : '{"AccessKey":"candoa01#gmail.com","Password":"candoa21"}'
})
.success(function(data){
console.log(data);
})
};
});
this is my php. i think here maybe I'm not using the right object name to retrieve the values.
public function login()
{
$data = $this->input->post('data');
//$data = '{"AccessKey":"candoa01#gmail.com","Password":"candoa21"}';
$data = json_decode($data);
$AccessKey = $data->AccessKey;
$Password = $data->Password;
$sql = "SELECT *
FROM Employees
WHERE Employees.AccessKey = ?
AND Employees.Password = ?";
$query = $this->db->query($sql, array($AccessKey, $Password));
if($query->num_rows() > 0)
{
$query = json_encode($query->result());
return $this->output
->set_content_type('application/json')
->set_output($query);
}
else
{
return 'Invalid AccessKey Or Password';
}
}
}
Try this, use params instead of data & remove ' in params
$http({
url: 'http://localhost:8888/employees/login',
method: "POST",
params: {"AccessKey":"candoa01#gmail.com","Password":"candoa21"}
})
As per your sever side code you have to pass the data as show below.
$scope.processForm = function(){
$http({
method : 'POST',
url : 'http://localhost:8888/employees/login',
data : {
data: JSON.stringify({
AccessKey: "candoa01#gmail.com",
Password:"candoa21"
})
}
})
.success(function(data){
console.log(data);
})
};
You receiving data wrong way because you are not posting data json format.This should be
$AccessKey = $this->input->post('AccessKey');
$Password = $this->input->post('Password ');
Or you can use this way
$data = $this->input->post();
$AccessKey = $data['AccessKey'];
$Password = $data['Password'];