I'm using Codeigniter and Jquery ajax for calling data from mysql and send to html form.
Problem: I Don't know how to call data from res object.
Here is my contrller
public function select_post(){
$data = $this->ads_m->get_post('ads',array('user_id'=> $this->user->user_id()));
IF($data){
foreach($data as $row ){
$response = array(
'name'=>$row->name,
'price'=>$row->price,
'addr'=>$row->des,
'img'=>$row->img,
'status'=>$row->status,
);
echo json_encode(array('res'=>$response));
}
}else{
echo json_encode(array('res'=>FALSE));
}
}
And here is Model function
public function get_post($from, $where = False) {
$this->db->select("*");
$this->db->from($from);
if ($where) {
$this->db->where($where);
}
$q = $this->db->get();
if($q->num_rows()>0){
return $q->result();
}
}
And this is Ajax
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: '<?php echo base_url('ads/select_post'); ?>',
data: {},
dataType: "json",
cache: false,
success: function (data) {
console.log(data.['res']['name']);
}
});
});
and I get the result as below
{"res":{"name":"dfasdfas","price":"0","addr":"sadfdfasdfasdf","img":"","status":"1"}}{"res":{"name":"Heng"
,"price":"0","addr":"asdfasfasdfasdfasdfasdfasfasdfasdfasdfasdfasfasdfasdfasdfasdfasfasdfasdfasdfasd
fasfasdfasdfasdfasdfasfasdfasdfasdfasdfasfasdfasdfasdfasdfasfasdfasdfasdfasdfasfasdfasdfasdfasdfasfasdfasdfasdf"
,"img":"","status":"1"}}{"res":{"name":"asdDasdA","price":"0","addr":"ASDasdASD","img":"","status":"1"
}}{"res":{"name":"asdfas","price":"0","addr":"dfasdf","img":"","status":"1"}}
// First change the response public function select_post(){
$data = $this->ads_m->get_post('ads',array('user_id'=> $this->user->user_id()));
IF($data){
var $responseArray = [];
foreach($data as $row ){
$response = array(
'name'=>$row->name,
'price'=>$row->price,
'addr'=>$row->des,
'img'=>$row->img,
'status'=>$row->status,
);
array_push($responseArray, $response);
}
echo json_encode($responseArray);
}else{
echo json_encode(array('res'=>FALSE));
}
}
//Then used below code to get the response in ajax
$(document).ready(function () {
$.ajax({
url: '<?php echo base_url('ads/select_post'); ?>',
data: {},
dataType: "json",
cache: false,
success: function (data) {
$.each(data, function(item) {
console.log(item.name);
});
}
});
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments