Converting JSON to HTML via AJAX in CodeIgniter

1

How do I use the JSON return in HTML? Here are the codes.

Ajax function:

$(document).ready(function(){
  $.ajax({
    url:"<?=base_url('pedido/listar');?>",          
    dataType: "html",
    success: function(data)
    {
      $('#pedidos').html(data);
    }
  });
});

Controller:

public function listar()
{   
    $this->pedido_model->listarPedidos();       
}

Model:

public function listarPedidos()
{
    $this->db->select('*');    
    $query = $this->db->get('pedidos');

    foreach ($query->result_array() as $pedido){
        $result[] = array('dados' => '<div class="card comandas text-center" href="#exampleModalCenter" data-toggle="modal">
            <div class="card-header">
            '.$pedido['cliente'].'
            </div>
            <div class="card-body">
                <h5 class="card-title">'.$pedido['idPedido'].'</h5>
                <p class="card-text badge badge-success">Aberto</p>
            </div>
        </div>');
    }

    echo  json_encode($result);
}
    
asked by anonymous 28.12.2018 / 16:40

2 answers

1

Change the dataType to "json" and then iterate with for...of by mounting the html and then inserting everything at once into the #pedidos element:

$(document).ready(function(){
  $.ajax({
    url:"<?=base_url('pedido/listar');?>",          
    dataType: "json",
    success: function(data)
    {
       var html = '';
       for(var item of data) html += item.dados;
      $('#pedidos').html(html);
    }
  });
});
    
28.12.2018 / 16:51
2

The select of your model would look like this (avoid consuming internet bandwidth) with information you do not use to mount HTML:

$this->db->select('cliente, idPedido');

The foreach of the model you would not use.

And in ajax you mount the element by adding it with a foreach on the return;

$(document).ready(function(){
   $.ajax({
    url:"<?=base_url('pedido/listar');?>",          
    dataType: "json",
    success: function(data)
    {
      console.log(data);
      // loop do conteudo da variavel data aqui
      $('#pedidos').append('<div>'+
        '<h2>HTML da lista vai aqui<h2>'+
      '</div>');
    }
  });
});
    
28.12.2018 / 17:01