I have a problem with my ajax, it can't display data from database.
Controller
public function rating() {
$rating = $this->db->select_avg('hasil_rating')
->get('tb_rating')->row_array();
echo json_encode($rating);
}
Ajax
function rate() {
$.ajax({
type: 'POST',
url: '<?php echo base_url()."rate/rating"?>',
dataType: 'json',
success: function(data) {
$('#aaaa').val(data);
}
});
input
<input id="aaaa" type="text" value="">
when I used val()
the result is [object Object] and when I used html()
the result is empty . But when I use console.log(data)
it works.
Just convert json object to string and it will work.
$('#aaaa').val(data.someVar);
For example,
var jsonVal = {val1:'one',val2:'two'};
alert(jsonVal); // it will print [object][object]
alert(jsonVal.val1); // one
alert(jsonVal.val2); // two
alert(JSON.stringify(jsonVal)) // it will print {val1:'one',val2:'two'}
Hope it will help you.
You need to first decode the json in your ajax success.
Use this.
function rate() {
$.ajax({
type: 'POST',
url: '<?php echo base_url()."rate/rating"?>',
dataType: 'json',
success: function(data) {
var d = $.parseJSON(data);
$('#aaaa').val(d.value);
}
});
Using this you can access different values from data and set the value in your html.
In your controller you can return the value using json_encode like
echo json_encode(array("success"=>true,"msg1"=>"test ajax","msg2"=>"test ajax 2"));
In your ajax success function to get the value of msg1 you can use
var d = $.parseJSON(data);
alert(d.msg1); //will return "test ajax"
alert(d.msg2); //will return "test ajax 2"
By this way you can access each and every value from your json object.
You have to require $.pasrseJSON before use the data
function rate() {
$.ajax({
type: 'POST',
url: '<?php echo base_url()."rate/rating"?>',
dataType: 'json',
success: function(data) {
data=$.parseJSON(data);
$('#aaaa').val(data.var_name);
}
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.