• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
(solved)help with jQuery, form plugin and cascade dropdown

#1
[eluser]jozeunico[/eluser]
Hi, well my problem it's probably that I don't understand good AJAX request with jQuery, even I don't have a clear idea about how to implement jQuery in CI.

I want to make dropdown in cascade (the most classic example it's when you choose your country and automatically populate a second dropdown with it states)

I have this view:
Code:
<html>
<head>
    [removed][removed]
    [removed][removed]

  
    [removed]
        $(document).ready(function() {
            var options = {
                target:        '#estados',   // target element(s) to be updated with server response
                beforeSubmit:  showRequest,  // pre-submit callback
                success:       showResponse  // post-submit callback
        
                // other available options:
                //url:       url         // override for form's 'action' attribute
                //type:      type        // 'get' or 'post', override for form's 'method' attribute
                //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
                //clearForm: true        // clear all form fields after successful submit
                //resetForm: true        // reset the form after successful submit
        
                // $.ajax options can be used here too, for example:
                //timeout:   3000
                


            };
          $('#myForm').ajaxForm(options);
          $("#id_country").bind("change", function(){          
              alert("hola");
           });
          


         });
            // bind form using 'ajaxForm'
//        $("id_countrys").change('#myForm');


        /*$('#myForm').submit(function() {
            // inside event callbacks 'this' is the DOM element so we first
            // wrap it in a jQuery object and then invoke ajaxSubmit
            $(this).ajaxSubmit(options);
    
            // !!! Important !!!
            // always return false to prevent standard browser submit and page navigation
            return false;
        }); */

//    });
    
    function showRequest(){
        //alert("hola");
         return true;
    }
    
    function showResponse(){
        //alert("hola2");      
    }
        
        
    [removed]
</head>
<body>
    <?php
    $attributes = array('class' => 'email', 'id' => 'myForm');
    echo form_open('comment', $attributes);
    ?>
    Name: <select name="id_country" id="id_country">
                <option value='1'>Mexico</option>    
                <option value='2'>E.U.A.</option>
            </select>
    <div id="estados">
        Estado:
    </div>
    &lt;input type="submit" value="Submit Comment"/&gt;
    <div id="comentario">
    </div>
&lt;/form&gt;
&lt;/form&gt;  
&lt;/body&gt;
&lt;/html&gt;

And this controller:
Code:
&lt;?php
class Comment extends Controller {
    
    function index(){
            $this->load->database();
            $this->load->model('UserModel');
            $lista_estados = $this->UserModel->getEstados($_POST['id_country']);
            $data="";
        foreach ($lista_estados->result() as $row){
            $data=$data.'<option value="'.$row->id.'">'.$row->estado.'</option>';
         }
        echo  'Estado:<select name="estado">'.$data.'</select>';
        
    }
}
?&gt;

and also here it's the model
Code:
&lt;?php
class UserModel extends Model{
    
    function getEstados($id_pais){
        $sql = "SELECT estado from estados where id_pais='$id_country';";
        $resultado = $this->db->query($sql);
           return $resultado;
    }

}
?&gt;

The database just have 2 tables (estados and pais) here it's the sql for create them and fill them
Code:
CREATE TABLE IF NOT EXISTS `estados` (
  `id_pais` int(11) NOT NULL,
  `id` int(11) NOT NULL auto_increment,
  `estado` varchar(35) collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=8 ;

--
-- Volcar la base de datos para la tabla `estados`
--

INSERT INTO `estados` (`id_pais`, `id`, `estado`) VALUES
(1, 1, 'Arteaga'),
(1, 2, 'Coahuila'),
(1, 3, 'Jalisco'),
(2, 4, 'Allende St'),
(2, 6, 'NavaYork'),
(2, 7, 'Sabinas City');

-- --------------------------------------------------------

--
-- Estructura de tabla para la tabla `pais`
--

CREATE TABLE IF NOT EXISTS `pais` (
  `id` int(11) NOT NULL auto_increment,
  `pais` varchar(35) collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `id` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=3 ;

--
-- Volcar la base de datos para la tabla `pais`
--

INSERT INTO `pais` (`id`, `pais`) VALUES
(1, 'Mexico'),
(2, 'E.U.A');

The only thing that my app do it's to populate the a second dropdown, but until make click on the submit button, i want to send the ajax request when change the first dropdown.

Well, any help thank you and thanks for your time too and I'm sorry about my english.

form plugin: http://malsup.com/jquery/form/#

#2
[eluser]nmormino[/eluser]
Seems to me like you're taking the round about way. I would forget the form plugin and just go with something like this

$(document).ready(function() {
$('#id_country').change(function() {


$.ajax({
type: "POST",
url: "some.php",
data: "country="+$('#id_country').val(),
success: function(data){
$('#estados').html(data);
}
});
});

what this function does is, when you select something from the first drop menu, it will send that value to whatever you have in your url field as post data, then take what that url returns and sticks it in your estados div. I haven't tested it, but it should do the trick.

#3
[eluser]jozeunico[/eluser]
Well, the reason because I didn't use that method it's, well even I am learning without "way", and now my doubt about that solution it's in the "url:"
what url use for set a function from a controller ? My controller it's called "comment.php" and the function where I make and echo it's "index"

I try with "comment/index", "comment","comment.php/index","comment.php" but nothing happend, Just that and thanks

#4
[eluser]jozeunico[/eluser]
Quote:Well, the reason because I didn’t use that method it’s, well even I am learning without “way”, and now my doubt about that solution it’s in the “url:”
what url use for set a function from a controller ? My controller it’s called “comment.php” and the function where I make and echo it’s “index”

I try with “comment/index”, “comment”,“comment.php/index”,“comment.php” but nothing happend, Just that and thanks

I solved the last doubt with this
Code:
CI_ROOT = "&lt;?php echo base_url() ?&gt;";

and then at the ajax request
Code:
url:CI_ROOT+"index.php/comment/index"

(http://ellislab.com/forums/viewthread/97212/)


Maybe it's not the best solution but it works.
Thanks a lot

#5
[eluser]nmormino[/eluser]
you're right on track with it, you could actually make it shorter by just using

url: "&lt;?= base_url()?&gt;index.php/comment";


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2019 MyBB Group.