Load more data from database with Codeigniter and Ajax

流过昼夜 提交于 2019-12-23 04:04:27

问题


I need help with a button for loading more data from the database. I've found examples, but too bad ones. Here is what I have so far:

The Ajax:

$('#revendas_conteudo .btn_carregar_mais').on('click', function(e) {
    $.ajax({
        url: '/auto/carros/load_more',
        data: {
            offset: $('#offset').val(),
            limit: $('#limit').val()
        },
        success: function(data) {
            $('#revendas_conteudo .lista_estoque').append(data);
        }
    });
});

My Controller method calling the Model load_more:

public function load_more()
{
    $offset = $this->input->get('offset');
    $limit = $this->input->get('limit');

    $data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
    $data['offset'] = $offset + 1;
    $data['limit'] = $limit + 1;

    echo json_encode($data);
}

Pesquisas_model::load_more():

public function load_more($offset, $limit)
{
    $this->db
        ->select(
            'usuario.nome_razao_social AS nome_anunciante,' .
            'modelo.modelo AS modelo,' .
            'marca.marca AS marca,' .
            'ano_modelo.ano AS ano,' .
            'ano_modelo.valor AS valor,' .
            'ano_modelo.combustivel AS combustivel,' .
            'cambio.descricao_cambio AS descricao_cambio,' .
            'estado.uf AS uf,' .
            'cidade.nome_cidade AS nome_cidade,' .
            'carro.*'
        )
        ->join('usuario', 'usuario.id = carro.id_usuario')
        ->join('ano_modelo', 'ano_modelo.id = carro.id_ano_modelo')
        ->join('modelo', 'modelo.id = ano_modelo.id_modelo')
        ->join('marca', 'marca.id_marca = modelo.id_marca')
        ->join('cambio', 'cambio.id = carro.id_cambio')
        ->join('estado', 'estado.id = carro.id_estado')
        ->join('cidade', 'cidade.id = carro.id_cidade')
        ->order_by('marca.marca', 'ASC')
        ->limit($offset, $limit);

    $query = $this->db->get($this->table);

    if ($query) {
        $data = array();

        foreach ($query->result_array() as $row) {
            $data[] = $row;
        }

        $query->free_result();

        return $data;
    }
}

The HTML:

<div class="lista_estoque">
    <?php foreach ($pesquisas as $p) { ?>
        <div class="item_estoque">
            <div class="avatar">
                <img src="/uploads/carros/destaque/<?php echo $p['imagem_destaque']; ?>"/>
            </div>
            <div class="texto_anuncio">
                <h4><?php echo $p['modelo']; ?></h4>

                <div class="detalhes">
                    <span><?php echo $p['marca'] . ' | ' . $p['combustivel'] . ' | ' . $p['cor']; ?></span>
                    <span><?php echo $p['ano']; ?></span>
                    <span><?php echo number_format($p['kilometragem'], 2) . 'km'; ?></span>
                </div>

                <span class="anunciante"><?php echo $p['nome_anunciante']; ?></span>
            </div>
            <div class="texto_anuncio_right">
                <span class="preco"><?php echo 'R$ ' . $p['preco']; ?></span>
                <a href="/comprar/detalhes/<?php echo $p['id'] ?>" class="bt_vejamais">Veja Mais</a>
            </div>
        </div>
    <?php } ?>
    <div class="carregar_mais">
        <input type="hidden" name="limit" id="limit" value="1"/>
        <input type="hidden" name="offset" id="offset" value="1"/>
        <button class="btn btn_carregar_mais" data-val="0">Mostrar mais resultados</button>
    </div>

So far what happens is a JSON code is appended to the end of the div. How do I make this data be converted into HTML and its classes?


回答1:


converting a json text to a java

var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

var obj = JSON.parse(text);

use the js object

<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>



回答2:


create a view called load_more.php in your view folder .. Your Controller will be like this

public function load_more()
    {
        $offset = $this->input->get('offset');
        $limit = $this->input->get('limit');

        $data['pesquisas '] = $this->Pesquisas_model->load_more($offset, $limit);
        $data['offset'] = $offset + 1;
        $data['limit'] = $limit + 1;

        data['load_more']=$this->load->view('load_more',$data);
    }

And in your view load_more.php

<?php foreach ($pesquisas as $p) { ?>
        <div class="item_estoque">
            <div class="avatar">
                <img src="/uploads/carros/destaque/<?php echo $p['imagem_destaque']; ?>"/>
            </div>
            <div class="texto_anuncio">
                <h4><?php echo $p['modelo']; ?></h4>

                <div class="detalhes">
                    <span><?php echo $p['marca'] . ' | ' . $p['combustivel'] . ' | ' . $p['cor']; ?></span>
                    <span><?php echo $p['ano']; ?></span>
                    <span><?php echo number_format($p['kilometragem'], 2) . 'km'; ?></span>
                </div>

                <span class="anunciante"><?php echo $p['nome_anunciante']; ?></span>
            </div>
            <div class="texto_anuncio_right">
                <span class="preco"><?php echo 'R$ ' . $p['preco']; ?></span>
                <a href="/comprar/detalhes/<?php echo $p['id'] ?>" class="bt_vejamais">Veja Mais</a>
            </div>
        </div>
    <?php } ?>

Jquery

     success: function(data) {
                      var res= JSON.parse(data);
                    $('#revendas_conteudo .lista_estoque').append(data.load_more);
     $('.carregar_mais input[name=limit]').val(data.limit);
   $('.carregar_mais input[name=offset]').val(data.offset);

});



回答3:


In the following function in controller, you need to add a view where you echo the content properly with html markups and classes as defined by you. Currently, you are echoing the json_encode format. That's why it is printing as it is.

    public function load_more()
{
    $offset = $this->input->get('offset');
    $limit = $this->input->get('limit');

    $data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
    $data['offset'] = $offset + 1;
    $data['limit'] = $limit + 1;

    //echo json_encode($data);
$this->load->view('load-more',$data['res']);
}




回答4:


Most of the answers here have led me to the solution. Sadly I can't tag all of them as the correct answer, so allow me to post what I did:

First, this is the full Ajax. I could not make it work with an external file as suggested, so it is like this:

$('#revendas_conteudo .btn_carregar_mais').on('click', function(e) {
    $.ajax({
        url: '/auto/carros/load_more',
        data: {
            'offset': $('#offset').val(),
            'limit': $('#limit').val()
        },
        success: function(data) {
            var obj = JSON.parse(data);
            var i = 0;
            var max = obj.total === obj.offset;

            $('#limit').val(obj.limit);
            $('#offset').val(obj.offset);

            $.each(obj, function(k, v) {
                $('#revendas_conteudo .load_more').append(
                    '<div class="item_estoque">' +
                        '<div class="avatar">' +
                            '<img src="/uploads/carros/destaque/' + obj.res[i].imagem_destaque + '"/>' +
                        '</div>' +
                        '<div class="texto_anuncio">' +
                            '<h4>' + obj.res[i].modelo + '</h4>' +

                            '<div class="detalhes">' +
                                '<span>' + obj.res[i].marca + ' | ' + obj.res[i].combustivel + ' | ' + obj.res[i].cor + '</span>' +
                                '<span>' + obj.res[i].ano + '</span>' +
                                '<span>' + obj.res[i].kilometragem + ' km</span>' +
                            '</div>' +

                            '<span class="anunciante">' + obj.res[i].nome_anunciante + '</span>' +
                        '</div>' + 
                        '<div class="texto_anuncio_right">' + 
                            '<span class="preco"> R$ ' + obj.res[i].preco + '</span>' +
                            '<a href="/comprar/detalhes/' + obj.res[i].id + '" class="bt_vejamais">Veja Mais</a>' +
                        '</div>' + 
                    '</div>'
                ).show('slow');

                i++;

                if (max) {
                    $('#revendas_conteudo .btn_carregar_mais').css({backgroundColor: '#999'}).html('Sem mais resultados').attr('disabled', true);
                }
            });
        }
    });
});

In here I append every new result to the div.load_more, and if the total is identical to the current offset, it means it has already shown all the values, making the button unavailable for clicking.

Here, the controller method:

public function load_more()
{
    $offset = $this->input->get('offset');
    $limit = $this->input->get('limit');

    $data['res'] = $this->Pesquisas_model->load_more($offset, $limit);
    $data['total'] = $this->Pesquisas_model->count_all();

    if ($data['res']) {
        $data['offset'] = $offset + 2;
        $data['limit'] = $limit;

        echo json_encode($data);
    }
}


来源:https://stackoverflow.com/questions/35413448/load-more-data-from-database-with-codeigniter-and-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!