bobthemac
bobthemac

Reputation: 1172

combining php ajax jquery for drop downs populated by sql

I am trying to get three different bits of php to work in order and work in a way that is easy for the user. This is the some of the code I have already that gets data from a database. I have a similar statement to this in a drop down that I need to populate using the answer from this first bit of code when it changes I also need to take the answers of both of these and put them into another sql statement that will display a set of results. I know I need to use something like jquery or ajax but I am unsure of how to use it in WordPress to get the desired effect.

<select name="raceTrack2" onchange="">
      <?php
            $postids = $wpdb->get_col("SELECT trackName FROM " . $trackTableName . ";");

            foreach ($postids as $value) 
            {
                echo '<option>' . $value . '</option>' ;

            }

      ?>
</select>

Any help would be appreciated

Upvotes: 0

Views: 283

Answers (1)

Edenbauer
Edenbauer

Reputation: 1344

There are several ways to skin this cat. Since you mentioned jQuery/Ajax I will guide you through the high level steps using those technologies:

  1. Write a javascript function that makes an Ajax call to a PHP script that returns the data in JSON format to populate your 2nd dropdown with. Inside your ajax() method, upon successful completion of the call, parse the JSON data and construct HTML code for the values for your 2nd dropdown. Then using jQuery selectors, select your 2nd dropdown and set the HTML contents of it using html() method.
  2. Modify the onchange() event handler for your 1st dropdown to call the JS function created in Step 1.
  3. Write another javascript function that grabs the selected value from your 1st dropdown and that from your 2nd dropdown. Then make another Ajax call to a PHP script that takes those two values as input and does whatever it needs to do with those values.
  4. Lastly, modify the onchange() event handler for your 2nd dropdown to call the JS function created in Step 3.

At a high level, this should do it. As I said, there are many ways to skin this cat. This is probably the simplest way to go and does not require a post-back/round-trip to your server.

Upvotes: 1

Related Questions