Ahmed Gaber
Ahmed Gaber

Reputation: 119

Fetch data using AJAX and Codeigniter?

I am trying to fetch data into a table and nothing happens.

  1. No table appears
  2. No data is fetched

Controller

  public function indexajax()
      {
        if($this->input->post("action")=='FetchAllUserUingAjax')
        {
            $this->load->model("usersmodel");
            $data["allu"]=$this->usersmodel->ShowAllUsers("users");
            $data['pagetitle']=" -->All Users Using Ajax<--";

           foreach ($allu as $a):
            echo'<tr>
            <td>'.$a->id.'</td>
            <td>'.$a->username.'</td>
            </tr>';
            endforeach;



            $this->load->view("template/admin/header",$data);
            $this->load->view("users/allusersusingajax",$data);

            $this->load->view("template/admin/footer");
        }



      }

jQuery

 <script>

        $(document).ready(function () {


            FetchAllUserUingAjax();
            function FetchAllUserUingAjax() {

                $.ajax({
                    url:'<?php echo base_url()?>Users/indexajax',
                    method:"post",
                    success:function (data) {
                        $(".userdataajax table").append(data);

                    }
                })
                var action="FetchAllUserUingAjax";
                $.ajax({
                    url:"<?php echo base_url()?>Users/indexajax",

                    method:"post",
                    data:{action:action},
                    success:function (data) {
                        $(".userdataajax table tr ").not("table tr:first").remove();
                        $(".userdataajax table").append(data);
                        Table();


                    }
                })

            }



        })

    </script>

Model

public function ShowAllUsers()
        {


            $sql=$this->db->get("users");
            return $sql->result();

        }

View

<div class="userdataajax table-responsive">
    <table class=" table table-responsive table-bordered">
        <tr>
            <th>#</th>
            <th>name</th>
            <th>image</th>
            <th> full name</th>
            <th>email</th>
            <th>usertype</th>
            <th>status</th>
            <th>reg date</th>
            <th>reg time</th>
            <th>delete</th>
            <th>edit</th>
            <th>Activate</th>
            <th>disactivate</th>

        </tr>




    </table>
</div>

Upvotes: 2

Views: 3859

Answers (2)

DFriend
DFriend

Reputation: 8964

Your code hints at other relevant code that is not shown. I'm taking what you show as all that needs to be known. Here's what I see based on that premise.

First, the view. Add an id to the table. It makes JQuery selectors so much easier. The JavaScript is in this file which is "users/allusersusingajax.php".

<div class="userdataajax table-responsive">
    <table id='user-table' class=" table table-responsive table-bordered">
        <tr>
            <th>#</th>
            <th>name</th>
            <th>image</th>
            <th> full name</th>
            <th>email</th>
            <th>usertype</th>
            <th>status</th>
            <th>reg date</th>
            <th>reg time</th>
            <th>delete</th>
            <th>edit</th>
            <th>Activate</th>
            <th>disactivate</th>
        </tr>
    </table>
</div>

<script>
    $(document).ready(function () {

        function FetchAllViaAjax() {
            $.ajax({
                url: '<?= base_url("users/get_all_users") ?>',
                method: "post",
                dataType: 'html',
                success: function (data) {
                    var table = $("#user-table");
                    table.not("table tr:first").remove();//your code makes it unclear why you need this 
                    table.append(data);
                }
            });

            FetchAllViaAjax();
        }
    });

</script>

The controller needs two methods. One to show the table another to get the rows. This is the file Users.php

//show the page which includes the basic <table> and header row
public function indexajax()
{
    // The code and question text give no reason for this conditional test 
    // So I'm removing it
    //if($this->input->post("action") == 'FetchAllUserUingAjax')
    //{
    $data['pagetitle'] = "-->All Users Using Ajax<--";
    $this->load->view("template/admin/header", $data);
    $this->load->view("users/allusersusingajax");
    $this->load->view("template/admin/footer");
    //}
}

//respond to ajax request
public function get_all_users()
{
    $this->load->model("usersmodel");
    $allu = $this->usersmodel->ShowAllUsers("users");

    $out = ''; //if the model returned an empty array we still have a string to echo
    //using PHP's output buffer to simplify creating a big string of html
    ob_start(); //start output buffering
    foreach($allu as $a):
        ?>
        <tr><td><?= $a->id; ?></td><td><?= $a->username; ?></td></tr>
        <?php
    endforeach;
    $out .= ob_get_clean(); //append the output buffer to the $out string
    echo $out;
}

Read about PHP's Output Control Functions

Upvotes: 1

Kisaragi
Kisaragi

Reputation: 2218

I'd first update my model to return an array:

return $sql->result_array();

Then in your controller, you don't need to load a view:

 public function indexajax()
 {
    if($this->input->post("action")=='FetchAllUserUingAjax')
    {
        //set content type
        header("Content-type: application/json");

        $this->load->model("usersmodel");

        echo json_encode(
            $this->usersmodel->ShowAllUsers(); //this method doesn't expect an argument, no need to pass one
        );

    }
  }

Then in your ajax callback:

success: function(resp){
   $.each(resp, function(k,v){
      console.log(v); 
   });  
}

Upvotes: 0

Related Questions