Displaying data from database with AJAX, jquery and codeigniter
ajax, codeigniter, jquery
Solution
You can extract data from the json by using `$.each`
success:function(data){
$('#result_table').append('<p>hello world</p>');
alert("Success!");
$.each(data.results, function(k, v) {
$.each(v, function(key, value) {
$('#result_table').append('<br/>' + key + ' : ' + value);
})
})
}
Problem
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: 'http://localhost:8888/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>' +results); alert("Success!"); } // 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(); $this->output->set_content_type('application/json'); $this->output->set_output(json_encode($data)); 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 } } ``` Okay so the AJAX returns the success alert, however instead of displaying the table from the database, this is what is displays in the div: Hello World null If I go directly to the url (http://loca.lhost:8888/index.php/trial/getValues) this is the object that appears: ``` { "results": [ { "qID": "1", "email": "hello", "qText": "hello", "playlistID": "", "timestamp": "0000-00-00 00:00:00" }, { "qID": "2", "email": "", "qText": "", "playlistID": "", "timestamp": "0000-00-00 00:00:00" }, } ``` How do I extract this info and display what I want to display?