1

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

1 Answer 1

3

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>
Sign up to request clarification or add additional context in comments.

4 Comments

I tried that but it still doesnt work, there's no longer a problem with value, but I still don't see my second dropdown. Could it be a problem in my ajax_call function?
could be, what do you get when you do a console.log(data); in your success callback?
I get this: `<html> <head> <meta name="author" content="Kai Oswald Seidler"> <meta http-equiv="cache-control" content="no-cache"> <title>XAMPP 1.7.7</title> <frameset rows="74," marginwidth="0" marginheight="0" frameborder="0" border="0" borderwidth="0"> <frame name="head" src="head.php" scrolling=no> <frameset cols="150," marginwidth="0" marginheight="0" frameborder="0" border="0" borderwidth="0"> <frame name="navi" src="navi.php" scrolling=no> <frame name="content" src="start.php" marginwidth=20> </frameset> </frameset> </head> <body bgcolor=#ffffff> </body> </html>´
just fixed it, there was an error with the url "text/ajax_call". I put the complete path instead (localhost/../text/ajax_call). Thanks for your help @swatkins!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.