Can't access the json values in my ajax success in codeigniter - php

now guys i know this is a simple error but no matter what i try i cant access the json values whenever i use alert after parse json it shows me undefined
why is it caused ?
here is my code
script
function getfriend_requests()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/getallfriends"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
var ParsedObject = JSON.stringify(data);
var json = $.parseJSON(ParsedObject);
alert(json);
$.each(json,function(key,data)
{
alert(data.object);
});
}
});
}
now the controller
public function getallfriends()
{
$id=$this->input->post('id');
$this->load->model('Pmodel');
$data['senders']=$this->Pmodel->get_all_user_friends_sender($id);
$data['recievers']=$this->Pmodel->get_all_user_friends_reciever($id);
echo json_encode($data);
}
now the model
public function get_all_user_friends_sender($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.senders_id = user_data.id');
$this->db->join('user', 'user_friend.senders_id = user.id');
$this->db->where('user_friend.senders_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
public function get_all_user_friends_reciever($id)
{
$this->db->select('*');
$this->db->from('user_friend');
$this->db->join('user_data', 'user_friend.recievers_id = user_data.id');
$this->db->join('user', 'user_friend.recievers_id = user.id');
$this->db->where('user_friend.recievers_id',$id);
$query = $this->db->get();
$row = $query->result_array();
// print_r($row);
return($row);
}
now when i try to return the value with result_array iy shows me undefined value but if i use $row_array it return only single value from each model.
can you tell me where i am going wrong?

You have array of objects in json response so in success function try like this..
$.each(json,function(key,data)
{
alert(data.key);//where key is key of pointing object
});

In your controller try to change
echo json_encode($data);
to
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode($data));

Related

i am getting error as trying to get property of non object

i am getting sql result as array..Then it show me an error like `
trying to get property of non-object in controller in
`$rate=$product_det->sale_rate;
This sale_rate is a field in my table product.I am new to PHP. Can anyone help?
My model:
function get_productDet($item)
{
$this->db->select('*');
$this->db->from('product');
$this->db->where('id',$item);
$res=$this->db->get()->result_array();
return $res;
}
My controller:
function product_det()
{
$item=$this->input->post('item_id');
$quantity=$this->input->post('quantity');
$rate=$this->input->post('rate');
$amount="";
$cgst="";
$sgst="";
$igst="";
$product_det=$this->sale_model->get_productDet($item);
if(!empty($product_det))
{
if($rate=="" || $rate==0)
{
$rate=$product_det->sale_rate;
}
$amount=$rate*$quantity;
$cgst_per=$product_det->CGST;
$sgst_per=$product_det->SGST;
$igst=0;
}
echo $rate."-".$amount."-".$cgst."-".$sgst."-".$igst."";
}
My javascript function:
$.ajax({
url: '<?php echo base_url(); ?>sales/product_det',
data: ({"item_id":item_id,"quantity":quantity,"rate":rate }),
dataType: 'html',
type: 'post',
success: function(data)
{
alert(data);
}
});
You are using result_array() in your sql query.
Then use foreach loop to show your record like this
if(!empty($product_det))
{
foreach($product_det as $p_det){
if($rate=="" || $rate==0)
{
$rate=$p_det['sale_rate'];
}
$amount=$rate*$quantity;
$cgst_per=$p_det['CGST'];
$sgst_per=$p_det['SGST'];
$igst=0;
}
}
Since apparently you only need details of one product.
Change:
$res=$this->db->get()->result_array();
To:
$res=$this->db->get()->row_array();
Then, the result is an array not an object. To access the returned elements do the following instead.
Change:
$product_det->sale_rate;
$product_det->CGST;
$product_det->SGST;
To:
$product_det['sale_rate'];
$product_det['CGST']
$product_det['SGST'];
Hope this will help you :
In model just Replace
$this->db->get()->result_array();
With
$this->db->get()->row();
Your model should be like this :
function get_productDet($item)
{
$this->db->select('*');
$this->db->from('product');
$this->db->where('id',$item);
$res = $this->db->get()->row();
return $res;
}

How to iterate over array of objects

I am calling a PHP function from a JQuery ajax method. Below is how the response looks from ajax call:
My question is: how to iterate over this array in jquery to get the values?
I am getting "Cannot use 'in' operator to search for 'length' in Array" if I iterate using $.each.
Below is the Code:
$("#member_country").change(function() {
var country = $(this).val();
//alert(country);
var ajax_url_mtypes = ins_membership_ajax.ajax_url;
//alert(ajax_url_mtypes);
jQuery.ajax({
url:ajax_url_mtypes,
data:{country:country,
action: "ins_get_membershiptypes_from_country"},
method:'GET',
contentType: "application/json;charset=utf-8",
success:function(response) {
//var resp = $.trim(response);
alert(response);
$.each(response, function( key, value ) {
alert( key );
alert( value );
});
}
});
PHP Code:
public static function getMembershipTypesNonAdmin($country){
$rtn = array();
global $wpdb;
$table = $wpdb->prefix.self::TABLE_NAME;
$query = "SELECT * FROM {$table} where admin_only = 'false' order by member_type";
$results = $wpdb->get_results($query);
if($results){
foreach($results as $row){
$membership_type = INS_Membership_Types::loadById($row->id);
$membership_type->setDues(INS_Membership_Types::getDuesByEconomy($country, $membership_type->getMemberType()));
$rtn[] = $membership_type;
}
}
return $rtn;
}
private $dues;
public function getDues()
{
return $this->dues;
}
public function setDues($dues)
{
return $this->dues = $dues;
}
You can iterate over objects through for in loop. like as below:
for(var prop in object){
console.log(object[prop]);
}
Hope this helps.
Try with json.
Use
json_encode()
in the php code and
dataType: "json"
in the ajax call

Codeigniter null values ajax request

, i'm triying to get some values from database on an ajax request in codeigniter...but json object returns null ([]) when I put console.log...I need help pls !!
JAVASCRIPT
function list_president() {
var section = "1";
$.post(baseurl + 'votos/load_politic', section,
function(data) {
console.log(data);
});
}
CONTROLLER
public function load_politic()
{
if ($this->input->is_ajax_request()) {
$section = $this->input->post('section');
$result = $this->politic->get_president($section);
echo json_encode($result);
}
}
MODEL
public function get_president($section){
$this->db->select("p.POLITIC_NAME, p.POLITIC_LASTNAME, p.POLITIC_SIDE, p.POLITIC_CHARGE");
$this->db->from("politics p");
$this->db->where("SECTION_ID",$section);
$result= $this->db->get();
return $result->result();
}
Thanks for help!!
You aren't sending key/value pair to server...just a value.
So there is no $_POST['section'] which is basically what $this->input->post('section'); is
Try changing
var section = "1";
To
var section = {section: "1"};
You also aren't validating what is sent or checking if $result returns anything

Codeigniter: Ajax data is printing in log but not working in function

I'm getting data through ajax who's function is:
<script type="text/javascript">
// Ajax post
$(document).ready(function()
{
$("#submit").click(function(event)
{
event.preventDefault();
var hiddenValue = $("#hiddenValue").val();
alert(hiddenValue);
var update_name = $("input#update_name").val();
// pop up Name Entered
alert(update_name);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "seasons/update_season",
data: {
hiddenValue : hiddenValue,
update_name: update_name
},
success: function(res)
{
console.log(res);
// window.alert("i got some data ");
if (res)
{
jQuery("div#result").show();
}
},
fail: function(res)
{
console.log(res);
}
});
});
});
The Controller function i have:
public function update_season()
{
$session_id = $this->session->userdata('id');
if (isset($session_id))
{
// print_r($_POST);
// die();
$update_id = $this->input->post('hiddenValue');
$update_name = $this->input->post('update_name');
$arr = array(
'id' => $update_id,
'name'=> $update_name);
//This prints empty data
// print_r($arr);
// die();
$result = $this->model_season->edit_season($arr);
// $result = $result->row();
if ($result)
{
print_r($arr);
}
else
{
return FALSE;
}
}
else
{
redirect('user_authentication');
}
}
And in Model through controller i have:
public function edit_season($data)
{
// I am getting right array of name and id
print_r($data);
die();
// but get empty variable if i try to assign value to it
$name = $data['name'];
$this->db->where('seasons', array('season_id ' => $data['id']));
$query = $this->db->update('seasons',array('names ' => $data['name'] ));
if ($query)
{
return $query;
}
else
{
return FALSE;
}
}
The ajax seem to work fine as its printing the values of id and name its getting i'm not even encoding it in json, but i'm unable to get its value in separate variable. I wonder if there is any different method to get values from ajax data ?
When i let it run the whole model function without making it die i have following error:
UPDATEseasonsSETnames= NULL WHEREseasons=Array``
Like array have nothing in it
There is error in your query, you are supplying array to where condition, where it should be string,
$this->db->where('season_id ', $data['id']);
Also, it is not good to have unnecessary spaces (though CI driver internally trims all spaces) in conditions like 'season_id ' should be 'season_id'
$this->db->where('season_id', $data['id']);
$query = $this->db->update('seasons', array('names' => $data['name']));
Check driver referance here: Queries in CI
$array1= array('season_id ' => $data['id']);
$array2= array('names' => $data['name']);
$this->db->where($array1);
$query = $this->db->update('seasons',$array2);

retrieve data from .post

I'm using codeigniter, I had a problem to process a data using jQuery $.post function. I want to send a value such as subjectid to ajax_get_subject_credit function and retrieve another field within same database table. The result shows on another text field. Here is my code.
View:
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(data){
$('#chours' + id).val(data); });
This get a value from drop-down and I want to make a text field automatic populate from drop-down. #chours is a text field ID.
Controller:
function ajax_get_subject_credit($result)
{
$this->db->select('subjectid, subjectcredit');
$query = $this->db->get('ref_subject');
$result = $query->result_array();
$query->free_result();
$subjectid = array();
foreach($result as $row)
{
$result = $result + array($row['subjectid'] => $row['subjectcredit']);
}
return $result;
}
Modified In Controller
I also tried using this statement in controller for direct calling the field but still no success :
function ajax_get_subject_credit($subjectid)
{
$this->db->select('subjectid, subjectcredit');
$this->db->where('subjectid',$subjectid);
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
echo $credithour;
}
I am going to provide a general example here
in view file
$.post('<?php echo site_url("test/test"); ?>', {'id':1}, function(response){
if(response.success)
{
alert(response.message);
} else
{
alert('Something went wrong!!');
}
}, 'json');
in controller Test.php
function test()
{
$id = $this->input->post('id');
//do additional stuff
$result = 'i am coming right out of controller!! ';
echo json_encode(array('success' => true, 'message' => $result));
}
Dont use return to return value to AJAX. use echo
change this,
return $result;
to
echo $result;
If you want your method to return an array that the javascript can use to populate a dropdown, you probably don't want to return a string.
Try something like this:
function ajax_get_subject_credit()
{
$query = $this->db->select('subjectid, subjectcredit')->get('ref_subject');
$result = $query->result();
$out = array();
foreach($result as $row) {
$out[$row->subjectid] = $row->subject_credit;
}
header('Content-Type: application/json');
echo json_encode($out);
}
This will return a JSON array to your view, which your javascript method can use to populate the dropdown with values and labels.
Here is my Result:
In View :
function subjectid_change(id, subjectid){
//Set value
setValue(id, subjectid);
$.post('<?php echo site_url('academic/ajax_get_subject_credit'); ?>', {'subjectid':subjectid}, function(response){
if(response.success)
{
$('#chours' + id).val(response.value);
} else
{
alert('Something went wrong!!');
}
}, 'json'); }
And my controller :
function ajax_get_subject_credit()
{
//Get Post Value
$subjectid = $this->input->post('subjectid');
//Select subjectid,subjectcredit FROM
$this->db->select('subjectid, subjectcredit');
//Where subjectid = 'subjectid'
$this->db->where('subjectid',$subjectid);
//Database name
$query = $this->db->get('ref_subject');
$credithour = $query->row()->subjectcredit;
$query->free_result();
$result = $credithour;
echo json_encode(array('success' => true, 'value' => $result));
}
Thanks to everybody who helped me.

Categories