2

I have an HTML listbox, I want to be able to select any value in that listbox and update a second listbox with a PHP database query based on that selection.

Options I have tried:

-I have tried using JSON. I update the second listbox using Javascript and calling an external PHP script, but the returned PHP value would be an array and that wont convert well with Javascript.

-I am not able to use cookies, so I use HTML Sessions. When you select a value in the first listbox it updates a session value and refreshes the page. Upon reload, the page does a PHP script using the Session value to update the second listbox, but I cant update the HTML Session with the selected value of the first listbox using Javascript by calling onChange="function(); with the first listbox".

Is there any other available options to implement this? Or how can I fix one of these options to make this work?

TrickyM66
  • 228
  • 3
  • 10

2 Answers2

1

You say that you've tried using JSON, but you clearly don't completely understand what that means. JSON is simply a way of formatting strings that can be understood universally by any machine which has a parser for it. The idea that the PHP value is an "array" and therefore unconvertible makes no sense; all that matters is that it's sent to the client in JSON format.

If you have an array in PHP, you can convert it to JSON format using the json_encode function:

<?php
my_arr = array('a' => 'b', 'c' => 'd');
// do stuff to fill array
echo json_encode($my_arr);
?>

When you receive it in JSON format in your JavaScript code, you can then parse it into a JavaScript object - see this question for details.

Community
  • 1
  • 1
Chris Hayes
  • 11,471
  • 4
  • 32
  • 47
1

So here is how I would do it using ajax. I would have an onChange event pass the value of the list to a hidden input. I would then post the input in the following manner.

var params = $('#hiddenInputId').serialize();
$.post('post.php', params, function(data){
                if(data.match(/^[\r\n\s]*OK=/)) {
                    $('#listOut').html(data.slice(data.indexOf('OK=') + 3));
                } 
                else if(data.match(/^[\r\n\s]*ERRORS=/)) {
                    alert(data.slice(data.indexOf('ERRORS=') + 7));
                }
}); 

The #listOut would point to a span or something that you want to fill in with your return select list. You would set up a if statement on the post.php page that listens for the submit of the hidden input and returns the correct value.

if(isset($_POST['hiddenInputName'])){
    $query = "SELECT * FROM table WHERE something LIKE'" . $_POST['hiddenInputName']."';";
    $result = mysql_query($query) or die(mysql_error());
    echo 'OK=created Select: <select>';
    while($row = mysql_fetch_array($result)){
        echo"<option value='" . $row['field_name'] . "'>" . $row['field_name'] ."</option>";
        }    
    }
    echo "</select>";
}
Blake Plumb
  • 6,779
  • 3
  • 33
  • 54