Reputation: 964
The model seems to be working as well as the controller. The AJAX displays the results as "null" so I think it is because we need to send the data as json. Any ideas on how to get the data into the correct format and to display in the view
View
<button type='button' name='getdata' id='getdata'>Get Data.</button>
<div id='result_table' style="color:white;">
hola amigo
</div>
<script type='text/javascript' language='javascript'>
$('#getdata').click(function(){
$.ajax({
url: '<?php echo base_url().'index.php/trial/getValues';?>',
type:'POST',
dataType: 'json',
error: function(){
$('#result_table').append('<p>goodbye world</p>');
},
success: function(results){
$('#result_table').append('<p>hello world</p>');
} // End of success function of ajax form
}); // End of ajax call
});
</script>
Controller
function getValues(){
$this->load->model('get_db');
$data['results'] = $this->get_db->getAll();
return $data;
}
Model
class Get_db extends CI_Model{
function getAll(){
$query=$this->db->query("SELECT * FROM questions");
return $query->result();
//returns from this string in the db, converts it into an array
}
}
Upvotes: 0
Views: 845
Reputation: 1858
In the controller just use this
function getValues(){
$this->load->model('get_db');
echo json_encode($this->get_db->getAll());
}
And in the view
success: function(results){
results = JSON.parse(results);
$('#result_table').append('<p>hello world</p>');
}
Upvotes: 0
Reputation: 2706
in your view, you set your data type to json so you need a controller that it's generate a json output. codeIgniter has a system to generate this type. you can use this code in your controller to do that:
$this->load->model('get_db');
$data = $this->get_db->getAll();
$this->output->set_content_type('application/json');
$this->output->set_output(json_encode( $data ));
and in ajax success get your response and use it:
success: function(response){
server_res = JSON.parse(response);
console.log(server_res);
$('#result_table').append('<p>hello world</p>');
}
Upvotes: 1
Reputation: 868
just print/echo the $data
in controller if you want html form(dont return). If you want json then print/echo json_encode($array)
and in success ajax write
success: function(results){
$('#result_table').append(results.arraykey);//arraykey=array key from controller
} // End
Upvotes: 0