drumichael611 drumichael611 - 4 months ago 16x
Ajax Question

CodeIgniter AJAX results writing to DIV

I have used this method in the past, but never with CodeIgniter. I'm just working on figuring out CI.

I have a very basic AJAX call for database results formatted in a datagrid.

Watching in the console, the expected results are showing up, however I just can't figure out why it won't write to my

. (I do get the alert that you see in the


var myOnload = function(){
url: 'http://contacts.drumichael.xyz/contacts/load_contacts',
type: 'post',
dataType: 'json',
data: {get_it: 'yes'},
}).complete(function(data) {

The controller looks like this: (simplified)

public function load_contacts() {
$query = $this->db->query("SELECT * FROM contacts_list");
$array = $query->result();

$return = '';

$return .= '<div class="panel-heading text-right"><a href="" class="btn btn-sm btn-primary btn-new"><i class="fa fa-plus"></i>&nbsp; &nbsp;New Contact</a></div>';
$return .= '<table class="table table-striped table-hover">';
$return .= ' <thead>';
$return .= ' <tr>';
$return .= ' <th></th>';
$return .= ' <th>Last Name</th>';
$return .= ' <th>First Name</th>';
$return .= ' <th>Cell</th>';
$return .= ' <th>Home</th>';
$return .= ' <th>Address 1</th>';
$return .= ' <th>Email</th>';
$return .= ' <th>URL</th>';
$return .= ' <th></th>';
$return .= ' </tr>';
$return .= ' </thead>';
$return .= ' <tbody>';

if(!empty($array)) {
foreach($array as $row) {
$return .= '<tr>';
$return .= '<td><i class="fa fa-pencil"></i></td>';
$return .= '<td>'.$row->lname.'</td>';
$return .= '<td>'.$row->fname.'</td>';
$return .= '<td>'.$row->phone1.'</td>';
$return .= '<td>'.$row->phone2.'</td>';
$return .= '<td>' .$row->address1. ' ' .$row->city.', ' .$row->state. ' ' .$row->zip. '</td>';
$return .= '<td>'.$row->email.'</td>';
$return .= '<td>'.$row->url.'</td>';
$return .= '<td><a href="" class="btn-delete" data-rec-id="'.$row->id.'"><i class="fa fa-trash"></i></a></td>';
$return .= '</tr>';
} else {
$return .= '<tr><td colspan="9">You don\'t have any contacts yet! Why not create some?</td></tr>';

$return .= '</tbody></table></div>';

echo $return;

In the view, I have
<div class="the_list"></div>
, however it never gets replaced with the HTML. Like I said earlier, I can see the HTML in the response section within my console in Firefox. Any ideas on what I've got wrong?


The problem is not specific for code Igniter, the problem in your ajax call. You are using .complete method which will return XMLHttpRequest object.
So, in your case you can use `


It will return the responded text. So, the modified code will be.

    $(document).ready(function() {
        var myOnload = function(){
             url: 'http://contacts.drumichael.xyz/contacts/load_contacts',
             type: 'post',
             dataType: 'json', // need not to specify if you are not returning json 
             data: {get_it: 'yes'},
          }).complete(function(data, xhr, settings) {