How can we pass result data from CodeIgniter controller to AngularJS controller? - php

How can we pass result data from CodeIgniter controller to AngularJS controller? In CodeIgniter controller using jsonSuccess code here I'm passing data to AngularJS but I would like to pass different 3 variables
How do I need to pass them and how can I get data?
codeigniter controller code:
$siteName = $CI->config->item('siteName');
$siteURL = site_url();
if($data['status'] == 'success')
{
$result = $this->LowCredit_model->info($data['data']);
jsonSuccess($result,$siteName ,$siteURL,$result['succ_code'],$siteName,$siteURL);
}
Angular Controller code:
$scope.init = function() {
alert('init');
gdiztunnel.post(
'order/LowCredit', {
id: $configId
}
).then(
function success (response) {
response = response.data;
if(response.status == 'success') {
$scope.lowcreditCtrl.data = response.data;

I already gave you the solution this is Repeated Question
$data['siteName'] = $CI->config->item('siteName');
$data['siteURL'] = site_url();
if($data['status'] == 'success') {
$data['result'] = $this->LowCredit_model->info($data['data']);
jsonSuccess($data);
}

Related

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

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

Asynchronously query the database by using ajax and jquery and post the result back in codeigniter View

I've struggeled alot with this .
I wanna send an ID in the CI model and get the returned value via CI controller
My view is
<script type="text/javascript">
function showsome(){
var rs = $("#s_t_item option:selected").val();
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
contentType: 'json',
data: {item_id: rs},
success: function(output_string){
//$('#result_area').val(output_string);
alert(output_string);
}
});
}
</script>
My Controller method is
public function get_unit_item()
{
$received = $this->input->post('item_id');
$query = $this->units_model->get_unit_item($received);
$output_string = '';
if(!is_null($query)) {
$output_string .= "{$query}";
} else {
$output_string = 'There are no unit found';
}
echo json_encode($output_string);
}
And my model function responsible
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() >0 ){
$j = $result->row();
return $j->unit_item_info ;
}
}
Html codes
<?php $id = 'id="s_t_product" onChange="showsome();"';
echo form_dropdown('product_id[]', $products, $prod,$id); ?>
I tried to use the id only but failed to fire so passing a function onchange seems to pick the item and fire
Using firebug I can see that the post request sends item_id=2 but the response length is 0 and with php result code 302
POST
RESPONSE
How can I achive this?(The model is loaded on the contructor)
Do slighly change your controller and model:
// Model
public function get_unit_item($where){
$this->db->where('item_id',$where);
$result = $this->db->get($this->tablename);
if($result->num_rows() > 0 ) {
$j = $result->row();
return $j->unit_item_info ;
}
else return false;
}
// Controller
public function get_unit_item()
{
$received = $this->input->post('item_id');
$return = array('status'=>false);
if( $query = $this->units_model->get_unit_item($received) ) {
$return['status'] = true;
// Add more data to $return array if you want to send to ajax
}
$this->output->set_content_type("application/json")
->set_output(json_encode($return));
}
Check returned values in JavaScript:
$.ajax({
url : base_url+ '/' + controller+ '/get_unit_item',
type:'POST',
dataType: 'json',
data: {item_id: rs},
success: function( response ){
if( response.status === true ) {
alert('Everything Working Fine!');
console.log( response );
}
else alert('Something went wrong in query!');
}
});
After trying various approaches I have finally found what really is the problem and i think this might be the problem for all with the 302 found error. In this project (server) there're two systems within the same root and each has got its own codeigniter files. As seen above i was using
var controller = 'items';
var base_url = '<?php echo site_url(); ?>';
url : base_url+ '/' + controller+ '/get_unit_item',
as the value for url but i tried to put the full url from the base and it worked so now it is
url: '<?php echo base_url(); ?>index.php/en/items/get_unit_item',
. I think for any one with the redirect issue the first thing to check is this

store form data in mysql database using ajax in codeigniter

Edit:
It was a problem with localhost and I think with the htaccess file. Although I couldn't make it in localhost, the script is running fine on the web host.
I want to store my form data in to the database using ajax in codeigniter. The problem is that everything is fine, except I'm getting a 500 server internal error.
My contoller:
public function order()
{
$order = $this->main_model->order($_POST);
if($order)
{
return true;
}
else
{
return false;
}
}
my model:
function order($options = array())
{
$options = array(
'client_Name' => $this->input->post('oName'),
'client_Phone' => $this->input->post('oPhone')
);
$this->db->insert('md_orders', $options);
return $this->db->insert_id();
}
and of course I'm using stepsForm script and this is the js code I have:
var theForm = document.getElementById( 'theForm' );
new stepsForm( theForm, {
onSubmit : function( form ) {
var form_data = {
oName: $('#oName').val(),
oPhone: $('#oPhone').val(),
};
$.ajax({
url: "<?php echo base_url() . 'main/order/'; ?>",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
}
} );
and this is the HTML code:
<form id="theForm" class="simform" autocomplete="off">
<ol class="questions" id="questions">
<li>
<span><label for="oName">Your name:</label></span>
<input class="finput" id="oName" name="oName" type="text"/>
</li>
<li>
<span><label for="oPhone">Your Phone Number:</label></span>
<input class="finput ltr" data-validate="number" id="oPhone" name="oPhone" type="text"/>
</li>
</ol>
</form>
and the error I'm getting is :
POST http://localhost/123/main/order/ 500 (Internal Server Error)
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
and nothing is stored in the database. What am I doing wrong?!
Try to check your input in controller before send it to model, although it is not mandatory. In your model you need just feed of your array. So you can just set name of parameter.
Your model something like this:
public function order($options) {
$data = array();
$data['client_Name'] = $options['oName'];
$data['client_Phone'] = $options['oPhone'];
$this->db->insert('md_orders', $data);
if($this->db->affected_rows() > 0) {
return $this->db->insert_id();
else {
return false;
}
}
Your controller something like this:
public function order() {
$order = $this->main_model->order($this->input->post());
if( $order !== false ) {
echo "Inserted!";
} else {
echo "Not inserted!";//These are your ajax success function msg parameter
}
}
Also, I can't see the logic of form parameter inside onSubmit property's function( form ). Maybe you could remove it?
In your view,place the following code in your script,please...
one_field = $('#one_field').val();
second_field = $('#second_field').val();
$.ajax({
type:"post",
data:{one_field:one_field, second_field:second_field},
url :'<?=base_url("directory/controller_name/your_method_name")?>',
success: function(data)
{
alert("success");
}
});
Now the place the following in your controller.
function your_method_name()
{
$your_data = array(
"table_field_1" => $this->input->post('one_field'),
"table_field_2" => $this->input->post('second_field')
);
$last_id = $this->your_model->insert_data_function($your_data);
if(isset($last_id)
{
//your code
}
else
{
//your code
}
}
In your Model,place the following.
public function insert_data_function($your_data)
{
$this->db->insert("your_table",$your_data);
return $this->db->insert_id(); //will return last id
}
Instead of using base_url() in your JS, you should try and use site_url()
Your CodeIgniter website runs through the index.php file.
The base_url() function will return the URL to your base directory.
The site_url() will return the URL to your index.php file.
Your form is trying to access "http://localhost/123/main/order" when it should be trying "http://localhost/123/index.php/main/order"
Hope this helps.
Edit
You should also have a look at the form helper.
https://ellislab.com/codeIgniter/user-guide/helpers/form_helper.html

Zend Json render data into views

Hi i have an Zend Framework apps, the following code are popularAction controller
public function popularAction()
{
$type = $this->_getParam('ref',1);
if($type == 'reviews'){
$businessReviewMapper = new Application_Model_Mapper_BusinessReviewsMapper();
$result = $businessReviewMapper->getTotalVote();
$rotd = $businessReviewMapper->getROTD($result['review_id']);
$rotd[0]['u_img'] = $this->view->getLoginUserImage($rotd[0]['social_id'],$rotd[0]['login_type'],null,null,square);
$rotd[0]['rating'] = $this->view->getRatingImg($rotd[0]['rating']);
$rotd[0]['business_name_url'] = preg_replace("![^a-z0-9]+!i","-", $rotd[0]['business_name']);
$this->render('reviews');
$this->_helper->json($rotd);
} elseif($type == 'openings') {
$this->view->text = "New Openings";
} else {
$this->_helper->redirector('index', 'index', 'default');
}
}
When a user browse to http://localhost/business/popular?ref=reviews the above controller code would render reviews.phtml template. Now inside the template itself there is ajax request for a data as follow:
function getPopular()
{
var count=1;
$.ajax({
url:"<?=$this->baseUrl('business/popular?ref=reviews')?>",
data:{'count':count},
dataType:"json"
type:"POST",
success:function(data){
alert('ok')
}
});
unfortunately the $this->_helper->json($rotd); doesn't pass data to the reviews.phtml,but display json data which is returned by zend db model, where i might be wrong?Thanks
If your Goal is to, to send JSON instead of the .phtml File on an Ajax Request, try to implement this:
if ($this->getRequest()->isXmlHttpRequest()) {
if ($this->getRequest()-isPost()) {
$this->_helper->json($rotd);
}
}
This part checks if the request is, lets call it: ajax based..

Categories