Dynamic Combobox Ajax Codegniter

0

Hello

I've already looked this question and did not answer me .

I have a select called Bank, as below and brings me the result OK:

<select id="banco" class="banco form-control" name="sel_banco_id" >
    <option value="0" disabled selected >Selecione</option>
    <?php foreach ($banco as $banco) {
         echo '<option value="'.$banco->id.'">'.$banco->nome.'</option>';
    } ?>
</select>

I need to do a dynamic select and depending on the selected bank, I want to% popular <select id="carteira" class="form-control" name="sel_carteira" > .

My table for the wallet is:

'id' INT(11) NOT NULL AUTO_INCREMENT,
'banco_id' INT(11) NULL DEFAULT NULL,
'carteira' INT(11) NULL DEFAULT NULL,
'situacao' TINYINT(1) NULL,

I have the following ajax code:

function obter_carteira_ajax(id, aguardar) {
    //Limpar
    $("#carteira :gt(0)").remove();
    if (id > 0){
        $.ajax({
            type: 'GET',
            contentType: 'application/json; charset=utf-8',
            async: !aguardar,			
	    url: 'boleto/buscar_carteira' + id,
            success: (function (data) {
                $(data).each(function () {
                    //Adiciona                    
		     $("#carteira").append("<option value='" + this.id + "'>" + this.codigo + "</option>");
                });
            }),
            error: (function (erro) {
                TrataErroAjax(erro);
            })
        });
    }
}

OR

function obter_carteira_ajax(id) {
    var id=id;
	    $.ajax({
            type:'POST',
            url:'boleto/buscar_carteira',
            data:{'id':id},
            success:function(data){
            //A próxima coisa que você quer fazer
        }
     });
}

I would like to know what the Controller and Model code should be, considering Ajax code:

public function buscar_carteira ()
{
    $id=$this->input->post('id',true);
    //Chamar Model
}
    
asked by anonymous 28.06.2017 / 01:07

1 answer

0

Good morning! I solved it as follows:

Ajax

function obter_carteira_ajax(id) {
    var id = id;
	$("#carteira :gt(0)").remove();
	if(id > 0) {
	    $.ajax({
            type:'GET',
            url:'boleto/buscar_carteira/' + id,
			dataType: "json",
            success:function(data){
				$('select[name="sel_carteira"]').empty();
				$.each(data, function(key, valor) {				
                $('select[name="sel_carteira"]').append('<option value="'+ valor.id +'">'+ valor.carteira + " " + valor.modalidade + '</option>');
            });
			error: (function (erro) {
                TrataErroAjax(erro);
            })
        }
    });
	} else {
        $('select[name="sel_carteira"]').empty();
	}
}

Controller

public function buscar_carteira ($id)
	{		
       $result = $this->db->where("banco_id",$id)->get("tbl_carteira")->result();
       echo json_encode($result);
	}
    
28.06.2017 / 14:46