简体   繁体   中英

Refreshing a specific div using jquery/ajax in codeigniter

I have a table with orders and i'm trying to refresh the table every 5 seconds without refreshing the whole page. After some research i found that i need to use this function:

<script>
$(document).ready(function(){
    refreshTable();
});
function refreshTable(){
    $('#the_div_you_need_to_refresh').load('path', function(){
        setTimeout(refreshTable, 5000);
    });
}

The problem is that i dont' really understand what should i put in .load('path') beacuse if i write it like this,it will double my header and it will give me an error:

.load('<?php echo base_url('page name')?>',function(){
         <--function content-->
})

My view page is this:

<h2><?= $title;?></h2>
<div id="table_container">
    <table class="table table-striped table-hover" id="orders_table">
        <thead>
        <--content-->
        </thead>
        <tbody>
        <?php foreach($orders as $order):?>
            <tr class="active">
                <--content-->
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>

And my controller is this:

public function index(){

            if(!$this->session->userdata('logged_in')){
                redirect('users/login');
            }
            $data['title'] = "Comenzi";
            $data['orders'] = $this->order_model->get_orders();

            $this->load->view('templates/header');
            $this->load->view('orders/comenzi',$data);
            $this->load->view('templates/footer');
        }

Can you explain to me how should i do this,please?

This is an asynchronous request which is used to get data from some other resource. In order to load fresh data after every 5 sec you need to create a page/controller which would be hit by this load function.

you need to enter the url of this page/controller in the path variable.

That controller is supposed to return the fresh data which you would append or replace using the jquery

try to create new action in your controller. for example.

public function newData(){

    if(!$this->session->userdata('logged_in')){
        redirect('users/login');
    }
    $data['title'] = "Comenzi";
    $data['orders'] = $this->order_model->get_orders();

    $this->load->view('path_to_your_table_view',$data);
}

in your script

<script>
    $(document).ready(function(){
        refreshTable();
    });

    function refreshTable(){
        $("#table_container").empty();
        $("#table_container").load("<?php echo base_url('newData')?>", function(){
            setTimeout(refreshTable, 5000);
        });
    }
</script>

i hope it will help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM