Himanshu Goyal Himanshu Goyal -4 years ago 121
Javascript Question

how to access only one object send by json not the whole array in ajax success function?

Hi guys i am trying to recieve data from controller to view using json_encode and ajax function but i am sending to separate values through json and tring to access it so how can i seprate those two objects and get only a single value.
let me show you my code

function check_relation_status()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/check_relation_status"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_Data = $.parseJSON(ParsedObject);
var senders_id=sender_Data.senders_id;

jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_senders_data"); ?>',
data:{id:senders_id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_values = $.parseJSON(ParsedObject);
var senders_name=sender_values.sender_data;
// alert(senders_name);
$.each(sender_values, function(key,data)
{
var uname = data.uname;
// alert(uname);

$('#friendship_request').append('<div>'+uname +'has sent you a request</div>');
});
}
});

}
});
}


now the controller code

public function get_senders_data()
{
$sender_id=$this->input->post('id');
$this->load->model('Pmodel');
$userdata=$this->Pmodel->getUserdata($sender_id);
$senders['senders_data']=$userdata;
$senders['senders_post'] = $this->Pmodel->get_all_count($sender_id);
// print_r($senders);
echo json_encode($senders);

}


the json value '$senders' holds both the values but when i try to access it usng 'each' function it shows the values two time when there is only a single column for uname . let me add some images to explain.

json response
view
can you tell me where i am wrong?

Answer Source

Try to change like below:-

if(uname){
$('#friendship_request').html('<div>'+uname +'has sent you a request</div>');
}

Note:-

1.You are appending all usernames (which is not correct).

2.You are not checking that username is either undefined or null or empty etc

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download