Ant100
Ant100

Reputation: 403

How to do a dynamic dropdown using Ajax in Codeigniter

I know this may be the [insertLongNumber]th time someone's ask this question, I did my research but I can't find another answer that fits my problem. So here it is.

I'm working on a dynamic dropdown with php and ajax, in codeigniter. I'm new to CI and I have a basic knowledge of Ajax.

What I have noticed so far is that in the console, it is not recognizing the value coming from the first dropdown, so i get departamento_id : undefined This makes me thing problem comes from ajax script (i got it of the web)

My view, with the ajax code included

<?php
$this->load->helper('html'); 
?>

<html>
<head>
    <title>Buscador</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#dpto-dropdown select').change(function () {
                var selDpto = $(this).attr('value');
                console.log(selDpto);
                $.ajax({
                    url: "test/ajax_call",
                    async: false,
                    type: "POST",
                    data: "departamento_id="+selDpto,
                    dataType: "html",

                    success: function(data) {
                        $('#ciudad').html(data);
                    }
                })
            });
        });
    </script>
</head>

<?php echo form_open('test/buscar');?>

<?php 

<div id='dpto-dropdown'><?php print form_dropdown('departamentos', $departamento) ?></div>


<div id="ciudad"><select><option value=''>-</option></select></div>
//rest of code...

This is my Controller code:

class Test extends CI_Controller 
{
function __construct()
{
    parent::__construct();
    $this->load->model('buscador_model');
}   

function index()
{
    $departamentos = $this->buscador_model->traerInfoDptos();
    $precios = $this->buscador_model->traerPrecioHoteles();

    foreach($departamentos as $departamento){
        $dpto_final[$departamento->id] = $departamento->nom_departamento;
    }

    $info = array(
        'departamento' => $dpto_final,
        'precios' => $precios,
    ); 

    $this->load->view('buscador_view', $info);
}

function ajax_call()
{
    //check to see people wont go directly
    if (isset($_POST) && isset($_POST['departamento_id'])) 
    {
        $dpto = $_POST['departamento_id'];
        $ciudad = $this->buscador_model->traerCiudadPorDpto($dpto);

        foreach ($ciudad as $c)
        {
            $ciudadfinal[$c->cod_ciudad] = $c->nom_ciudad;
        }

        //dropdown

        echo form_dropdown('Ciudades', $ciudadfinal);
    }
    else 
    {
        redirect('index');
    }
}
}

this is my model:

Class Buscador_model extends CI_Model
{

function traerInfoDptos()
{
    $this->db->select('id, nom_departamento');
    $this->db->from('departamento');
    $query = $this->db->get();

    if ($query->num_rows > 0)
    {
        return $query->result();
    }
}

function traerCiudadPorDpto($dpto)
{
    $query = $this->db->query("SELECT nom_ciudad, cod_ciudad FROM ciudad WHERE departamento_id = '{$dpto}'");

    if ($query->num_rows > 0)
    {
        return $query->result();
    }
}

}// end buscador model class

Upvotes: 1

Views: 13114

Answers (1)

swatkins
swatkins

Reputation: 13640

See this page: http://www.onerutter.com/open-source/jquery/jquery-tips-how-to-get-value-of-selected-option-in-select-box.html

You need to use .val() instead of .attr('value')

<script type="text/javascript">
    $(document).ready(function () {
        $('#dpto-dropdown select').change(function () {

            var selDpto = $(this).val(); // <-- change this line
            console.log(selDpto);

            $.ajax({
                url: "test/ajax_call",
                async: false,
                type: "POST",
                data: "departamento_id="+selDpto,
                dataType: "html",

                success: function(data) {
                    $('#ciudad').html(data);
                }
            })
        });
    });
</script>

Upvotes: 3

Related Questions