user2796352
user2796352

Reputation: 964

Displaying data from database with AJAX, jquery and codeigniter

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?

Upvotes: 4

Views: 32234

Answers (3)

Jakub
Jakub

Reputation: 20475

You're overcomplicating some things, update this to just output json:

controller:

function getValues(){
    $this->load->model('get_db');
    $data['results'] = $this->get_db->getAll();

    if($data['result']){   // we got a result, output json
         echo json_encode( $data['result'] );
    } else {
         echo json_encode( array('error' => true) );
    }
}

and your javascript will easily handle the result (since you pass back JSON = javascript object notation)

success: function(data){
    // handle the result
    var re = $.parseJSON(data);

    if(!re.error){
        // no error so lets put out some data whatever way
    }
}

Using var re = $.parseJSON(data); will easily let you access the json data in . form:

re.result etc;

Output the json to console.log(data) to see its structure (without printing it into your html). Use Chrome inspector to traverse your structure.

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

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);
        })
    })
}

Upvotes: 4

mr_mark88
mr_mark88

Reputation: 1059

Rather than returning $data from your controller, json_encode it and use echo instead.

function getValues(){
    $this->load->model('get_db');
    $data['results'] = $this->get_db->getAll();
    echo json_encode($data);
}

Hope that helps!!

Upvotes: 1

Related Questions