Converting JSON to HTML via AJAX into Codeigniter

Asked

Viewed 111 times

1

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

Ajax function:

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

Controler:

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);
}
  • The best thing to do is to return the object with the information and use this information in javascript to mount your html.... I will set an example and put as an answer.

2 answers

2

The select your model would look like this (avoid consuming band "internet") with information that does not use to mount HTML:

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

The foreach model you would not use.

And in ajax you assemble the element by adding with a foreach in 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>');
    }
  });
});
  • I’ll do it here to see. Thank you

  • Just a doubt, in js I’m half bad, as I would use the foreach in it?

1


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

$(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);
    }
  });
});
  • It worked. Thank you :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.