简体   繁体   中英

Dynamic Chained SELECT Boxes using jQuery

I am using a jQuery/JS/Ajax script to dynamically fill SELECT boxes from my database, with each subsequent SELECT box being populated based on the the previous SELECT.

Eg. Someone selects 'England' from my first SELECT, this then populates the next SELECT with towns in England etc.

The trouble I'm having is getting the second SELECT function to recognise a variable. It's a lot of code so I don't want to paste it all but... this is the first function which populates the first SELECT box on page load:

function getTierOne()
{   
 $tblname = $_SESSION['country'];
 $result = mysql_query("SELECT DISTINCT county FROM $tblname ORDER BY county") 
 or die(mysql_error()); 
 while($tier = mysql_fetch_array( $result ))  
 {
  echo '<option value="'.$tier['county'].'">'.$tier['county'].'</option>';
 }
}

This is fine, $tblname is a posted $_SESSION variable containing the users country, obvs.

The problem is 'onBlur' of this first SELECT box, a second SELECT box is brought up using this JS function and PHP call:

$(document).ready(function() 
{
    $('#wait_1').hide();
    $('#drop_1').change(function()
        {
            $('#wait_1').show();
            $('#result_1').hide();
            $.get("func.php", 
                {
                    func: "drop_1",
                    drop_var: $('#drop_1').val()
                }, 
            function(response)
                {
                    $('#result_1').fadeOut();
                    setTimeout("finishAjax('result_1', '"+escape(response)+"')", 400);
                });
            return false;
        });
});

...

if (isset($_GET['func'])&& $_GET['func'] == "drop_1") {
drop_1($_GET['drop_var']);
}

Which calls this function:

function drop_1($drop_var)
{  
  include_once('functions.php');
  $result = mysql_query("SELECT DISTINCT town FROM $tblname WHERE county='$drop_var'") 
  or die(mysql_error());

  echo '<select name="drop_2" id="drop_2">
  <option value=" " disabled="disabled" selected="selected">Select Your Town/Nearest Town</option>';

  while($drop_2 = mysql_fetch_array( $result )) 
  {
  echo '<option value="'.$drop_2['town'].'">'.$drop_2['town'].'</option>';
  }
  echo '</select>';
  echo '<input type="submit" name="submit" value="Continue" />';
}

But this function will not recognise my $tblname variable, even if i use Global! The only variable it recognises is $drop_var, which is the result of the first SELECT box.

Does anyone have any idea how i can pass the $tblname variable into

function drop_1($drop_var) { ...

If you're using PHP sessions to store the user's country (and from line1 of getTierOne() it looks like you are), you should be able to add the line to the start of your drop1() PHP function:

function drop_1($drop_var)
{  
  $tblname = $_SESSION['country'];
  include_once('functions.php');
  ...

Jquery should be sending your user's cookie along with the GET parameters (func and dropvar), which allows PHP to know which session belongs to the user, and give them their session variables back (You can check this with the "Network" tab of Firebug / Chrome inspector- look for the call to func.php after onBlur has fired and look for the "Cookie" request header).

Alternatively, if you're not using sessions, but you have the country stored on the client-side (eg. as the first "drop_0" select box?), you could have jquery pass the selections from tier1 (county) select boxes in the get call. ie.

$.get("func.php", 
{
  func: "drop_1",
  country: "VALUE OF COUNTRY HERE",
  drop_var: $('#drop_1').val()
}, 
function(response)
{ ...

And modify your server-side PHP code to accept 2 arguments instead of one.

From a maintainability point of view, consider not using multiple tables (one per country) and instead use a single table with an additional "country" column. It's rarely a good idea to have multiple identically structured tables, MySQL generally handles millions of rows much better than hundreds of tables, and it makes joins and making changes to your tables' structure more difficult. You also should be sanitizing the inputs, not using $GET['drop_var'] directly in a SQL query, or it'll break on quotes and opens you up to SQL injection attacks. (Apologies if you have a good reason for doing either of these: Obviously you know more about your specific requirements than I do!)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM