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));
}
Related
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;.
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.
suppose I have $data, which is a collection of entire data of a table, is it possible to pass this collection type data in parameters via URL from view to controller?
I'm using Laravel. All the solutions I've been searching only for array type data. Thanks for help!
You can. First install the package guzzlehttp/guzzle. then try this way:
use GuzzleHttp\Client;
$client = new Client();
$sampleData = ['name' => 'billy', 'email' => 'billy#example.com']; // your collection
$url = 'http://api.example.com/bla-bla'; // your url
$res = $client->request('POST', "{$url}",['form_params' => $sampleData]);
$data = json_decode(json_encode($res->getBody()->getContents()),true);
return $data;
Make a post request from your view to the required URL.
Example:
Adapted from here
<table id="tData">
<tbody>
<tr>
<td class='dataVal1'>100</td>
...
$(document).ready(function() {
var toServer = {};
var data = $('#tData tbody tr td').each(function(key, value) {
toServer[$(this).attr('id')] = $(this).text();
});
$.ajax({
url: '/test/',
data: {
"_token": "{{ csrf_token() }}",
"table_data": toServer,
}
type: 'POST'
})
});
Now in your controller which handles the page, use the following
public function test(Request $request)
{
dd($request);
}
Note: Make sure the URL which you mention in the ajax request can accept post request.
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"}';
}
}
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'];