I am trying to create a search where the user selects two different bits of data from the database and it then prints some results that meet requirements. I know I need to use AJAX, or something similar, but I have little idea how I should be doing it. The first dropdown box works fine, as that doesn't depend on anything. Here is the code for that:

<select name="raceTrack2" onchange="">
    <?php $postids = $wpdb->get_col("
        SELECT trackName 
        FROM " . $trackTableName . ";
    foreach ($postids as $value) {
        echo '<option>' . $value . '</option>' ;
    } ?>

That works fine. The next step is where it starts to get complicated. Now I need to take the value of the first selection box and add it into the SQL query of the next one, then run that query when the first selection box changes using onchange.

<select name="raceDate">
    <?php $postids2 = $wpdb->get_col("
        SELECT DISTINCT raceDate 
        FROM " . $tableName . " 
        WHERE trackName = '" . $track . "';
    foreach ($postids2 as $value2) {
        echo  $value2  ;        
    } ?>

Then I need to take the value of both of these dropdowns and use them in this final query to display the results:

$postids = $wpdb->get_results("
    SELECT driverName, driverClass, driverPosition 
    FROM " . $tableName . "
    WHERE trackName = '" . $track . "' AND raceDate = " . $date . ";
foreach ($postids as $value) {
    echo '<tr valign="top">';
    echo '<td>' . $value->driverName . '</td>';
    echo '<td>' . $value->driverClass . '</td>';
    echo '<td>' . $value->driverPosition . '</td>'; 
    echo '</tr>';

Any suggestions would be appreciated.

  • I am not sure from your question - is it about implementing Ajax at all, Ajax in WP or something else? – Rarst Aug 8 '12 at 18:33
  • I need to implement Ajax in Wordpress to run SQL querys live onon change but I don't know how to do this. – bobthemac Aug 9 '12 at 13:01
  • When you are dealing with user input, you really should be using $wpdb->prepare() inside your get_col method. – Marc Dingena Feb 18 '14 at 9:38

You are giving your own solution here. Use the onchange event for the dropdowns, or the .change event in the jquery API.

Otherwise, this is called 'cascading' - dropdowns.

Also, I don't think this has anything to do with wordpress. Similar to this question

  • I am asking how to do it in Wordpress as Wordpress has features for Ajax built in but I don't know how to use them and the codex is worse than useless to me it's about passing php variables live through my code in Wordpress. – bobthemac Aug 9 '12 at 13:03
  • Please use proper upper-/lowercase and the possibilities the WYSIWYG editor is offering you (marking code as such, etc.). Thanks. – kaiser Sep 11 '12 at 1:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.