-1

I've been looking at a dozen or more php mysql jquery ajax tutorial sites/plugins but all of them seem to be hard coding the values or value sets into ajax/jquery/json rather than just link the drop downs as I require. I also checked stackoverflow whether there was anything, but the examples were all hardcoded.

Desired workflow

1. Select value in drop down 1
2. define a variable in drop down 2 or in mysql select that takes value from drop down 1 and limit the options or change the options as required

Relevant Database Structure

Table : price_change 
ID | price_word  | amount     | max_
3  | 10 Lacs     | 1000000    | 0
4  | 25 Lacs     | 2500000    | 0
1  | >10 Lacs    | 999999     | 0
2  | 1 Crore     | 10000000   | 1
11 | 10 Crores   | 100000000  | 1
10 | 5 Crores    | 50000000   | 1
7  | 1.25 Crores | 12500000   | 2
8  | 1.5 Crores  | 15000000   | 2
9  | 2 Crores    | 20000000   | 2
5  | 50 Lacs     | 5000000    | 2
6  | 75 Lacs     | 7500000    | 2

I have a prepared statement that selects the data and displays results as per the query

function db_select($query) {
    $rows = array();
    $result = db_query($query);

    // If query failed, return `false`
    if($result === false) {
        return false;
    }

    // If query was successful, retrieve all the rows into an array
    while ($row = mysqli_fetch_assoc($result)) {
        $rows[] = $row;
    }
    return $rows;
}

Current code for generating values for drop down 1

<select name="minprice" id="minprice" >
    <?php
        $rows = db_select("SELECT amount,price_word FROM price_change where max_<>'1' ");
        foreach($rows as $row){
            echo "<option value='".$row['amount']."'>".$row['price_word']."</option>";
        }
    ?>
</select>

Current code for generating values for drop down 2

<select name="maxprice" id="maxprice">
    <?php
        $rows = db_select("SELECT amount,price_word FROM price_change where max_<>'0' ");
        foreach($rows as $row){
            echo "<option value='".$row['amount']."'>".$row['price_word']."</option>";
        }
    ?>
</select>

In order for drop down 2 to always be more than drop down 1, I need to define a variable that can be used to ensure this. so ideally it would be like this SELECT amount,price_word FROM price_change where max_<>'0' AND amount>=$dropdown1

I know this will involve some ajax/jquery but I want to ensure that the code is reusable so I don't hard code the values or select elements.

Can someone please point me in the right direction as I have been trying to do this for hours

I hope there is enough information to assist me in a solution, but if I missed something and if there is a better way to do this, please let me know.

EDIT - This works - http://www.plus2net.com/php_tutorial/dd.php but the only problem is that it runs a simulation of page refresh with new url which I don't want. I basically want the URL to be the same. But this is a step in the right direction as it doesn't hard code the values or selects or anything

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
Saud Kazia
  • 192
  • 2
  • 15
  • 1
    The maturity is just great here. At least tell me why this is down voted so I can correct it. I have given all the information required or asked to request for more information. What do I have to do now. If you look back at the most useful questions in google, they don't even have code and just ask for a helping hand, those are the questions that have helped me the most and I'm sure others have benefited as well. I remember a time, where a answer or two or three was given in a matter of minutes and not down voted. Wonder what happened. – Saud Kazia Feb 04 '15 at 16:30
  • Quite a bit to do here. First start off by creating a server side php file that takes a param such as `$_POST['dropdown1']` then put an `onchange` listener on your dropdown one that does an ajax call to the script, lets call it options.php for example, and passes dropdown1 and it's value, then have that function then create the options and have it update the dropdown2. I think the downvote may have come from the fact that this you can find a lot of tutorials on what ajax is http://www.w3schools.com/php/php_ajax_database.asp for example. Instead of displaying text, you modify your options. – Dave Goten Feb 04 '15 at 16:34
  • hi dave . thanks for your comment. but are you telling me that such a simple result will require so much code. i thought it would be just a jquery plugin that I would use that will basically emulate a refresh of the sql code based on the dropdown value. im not so versed with all this, but just wanted a step in the right direction. but still no reason to downvote without a clear reason why. and about the tutorials, i couldn't find anything as per what I wanted to do. Like I said, I have seen and even downloaded over a dozen such tutorials/plugins – Saud Kazia Feb 04 '15 at 16:44
  • I think @DaveGoten is on the right track with the exception of recommending w3schools. You you can populate drop-down 1 with values from PHP/MySQL. Then you capture the value selected when DD1 changes and utilize that value (along with other info) to generate an AJAX call to PHP for creating/populating DD2. No hard-coding of any values is required, just the output of PHP. – Jay Blanchard Feb 04 '15 at 16:50
  • Hi Saud, there's a jquery built-in function http://api.jquery.com/jquery.ajax/ that does ajax but you didn't tag jquery so I was giving you a vanilla resource. I didn't downvote you, not that that matters, but I after being here for a little while I do understand that people tend to downvote when they think a question can be answered by reading the manual as they often say. Check out that link and it'll show you how to use the method, and also check http://stackoverflow.com/questions/22906249/jquery-ajax-populate-dropdown-with-json-response-data for some ideas – Dave Goten Feb 04 '15 at 16:53

1 Answers1

1

You should focus on your code indentation :)

I believe related select is what you are looking for and here is how it can be done.

If what you want is to filter the value of drop-down 2 based on the selection of a value from drop-down 1, we can go about like this.

//Drop-down1
<select name="minprice" id="minprice" >
    <?php
        $rows = db_select("SELECT amount,price_word FROM price_change where max_<>'1' ");
        foreach($rows as $row){
            echo "<option value='".$row['amount']."'>".$row['price_word']."</option>";
        }
    ?>
</select>

//Drop-down2
<select name="maxprice" id="maxprice">
    <?php
        $rows = db_select("SELECT amount,price_word FROM price_change where max_<>'0' ");
        foreach($rows as $row){
            echo "<option value='".$row['amount']."'>".$row['price_word']."</option>";
        }
    ?>
</select>

At this point we require javascript/ajax to do the job for us, what we'll do is.

  • Capture "on-change" trigger from the first select element.
  • Send an ajax request along with the selected value from first element.
  • On receiving the response, re-populate drop-down 2 with the new data.

Although, ajax can be implemented using plain JavaScript, I prefer jQuery to do the job, hence make sure in the same page, you have included the jQuery library, otherwise the code won't work.

<script type="text/javascript">
    //Execute this when DOM is loaded.
    $(document).ready(function(){
        //Trigger an on-change even from the first drop-down.
        $('#minprice').on('change', function() {
             //Fetch the current selected value.
             var value = $(this).val();
             //Send an ajax request with the selected value.
             $.ajax({
                 url: 'ajax.php',
                 data: 'minprice='+value,
                 method: 'POST',
                 success: function(response) {
                     //Received response from the script, time to re-populate drop-down2 with the new content received from the script.
                     //Step1- Remove all existing options from drop-down 2
                     $('#maxprice').find('option').remove();
                     //Step2 - Populate drop-down 2 with received content using the loop.
                     $.each(response, function(index, value)) {
                         $('#maxprice').append('<option value="'+index+'">'+value+'</option>');
                     }
                 }
             });
        });
    });
</script>

Lastly, you need to create a file named ajax.php, so you can receive and send the server content, ajax.php can be something similar to this.

//Filename: ajax.php
//Store the received value in a variable.
$minprice = !empty($_POST['minprice']) ? (int)$_POST['minprice'] : die('empty minprice');
//Initialize an empty array to return.
$result = array();

//Run the database query with the minprice value and assign retrieved value to $result, in the end echo $result in this file, like the following.

//Make sure the array returned is in following format.
$result = array(
    '1000000' => '10 Lacs',
    '2500000' => '25 Lacs',
);
echo $result.

PS: This code is not tested, but hoping it should run.

Hope this helps.

Ibrahim Azhar Armar
  • 25,288
  • 35
  • 131
  • 207
  • This code is not reusable. I've already seen such code but see how ajax.php is hard coding the values and selects. Please see my edited post with link. I dont want any hard coded values selects or any orher information that cannot be usable with multiple selects. Maybe im asking for too much – Saud Kazia Feb 05 '15 at 16:47
  • tested. your link. only the last option works. will try it and see – Saud Kazia Feb 05 '15 at 16:58