Save data to MySQL - json_encode - php

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.

Related

How do I return JSON data from CodeIgniter to Google Apps Script?

so we've been making a chatbot in Google Apps Script and one of its functions is to display information from a database (hosted online). The script sends a POST request to a controller function in our CodeIgniter program:
function do_post(name, status, duration) {
// Make a POST request with a JSON payload.
var data = {
'name': name,
'status': status,
'key' : api_key,
'duration' : duration
};
var options = {
'method' : 'post',
'contentType': 'application/json',
'muteHttpExceptions' : true,
// Convert the JavaScript object to a JSON string.
'payload' : JSON.stringify(data)
};
var response = UrlFetchApp.fetch('https://www.domainname.com/bot/index.php/bot/process/', options);
Logger.log(response);
return response;
}
The function above successfully inserts a record into the database using our process() controller in CI, but the problem is in our response variable. It's of HttpResponse type and we don't know how to return that type from our controller. We want our controller to return something like {"Response": "success"} to our chatbot but we don't know how. We've tried returning a JSON-encoded array:
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
$res_array = array("response" => $result);
// encode array to json
$json = json_encode($res_array);
return ($json);
}
}
And we try accessing var response in our app script using response.getContentText(), but we get something like "string(39)" and then the value of our api_key. How do we access the json data from the response?
You need to set the mime-type of your page so you can serve JSON data by using the set_content_type() method from the Output class.
Check the code
public function process()
{
$_POST = array_replace($_POST, json_decode(file_get_contents('php://input'), true) ?? []);
$name = $_POST["name"];
$status = $_POST["status"];
$api = $_POST["key"];
$duration = $_POST["duration"];
if ($api == api_key){
$result = $this->bot_model->add_log();
}
// JSON OUTPUT
$this->output
->set_content_type('application/json')
->set_output(json_encode( array("response" => $result)));
}
I noticed that when a function in CodeIgniter is called via post, the return of that function is whatever is printed out by the function in any way, be it echo, print_r, or var_dump. So to return your JSON file to App Script simply do echo $json;.

Get params from angular $http in Codeigniter controller

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));
}

Codeigniter Post data using AngularJS

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"}';
}
}

Ajax + PHP: null instead of an array

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'];

angular how to pass an object in an ajax post

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'];

Categories