Dynamic Combobox Ajax Codegniter

Asked

Viewed 346 times

0

Hello!

I’ve already looked this question and won’t 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 make 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’d like to know what the code of Controller and Model, taking into account the Ajax code:

public function buscar_carteira ()
{
    $id=$this->input->post('id',true);
    //Chamar Model
}

1 answer

0

Good morning! I solved it this way:

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);
	}

Browser other questions tagged

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