RPeraltaJr
12/18/2019 - 4:12 PM

Fetch data dynamically with AJAX depending on another select option

Feature:

  1. User selects a location
  2. Dynamically load all available categories based on location selection
/*
| -------------------------------------------------
| Location & Category
| -------------------------------------------------
*/

// hide by default
$("[data-form-careers]").hide();

$(document).ready(function() {
  $("select[name='location']").change(function() {
    let location = $(this).children('option:selected').text();
    let formContainer = $(this).parent().parent();
    // console.log(formContainer);
    let categorySelect = formContainer.find("select[name='type']");

    if(location !== "") {
        $(this).parent().next().show();
        $.ajax({
            type: "POST",
            dataType: "json",
            url : "/bayard/serviceking/wp-admin/admin-ajax.php",
            data : { 
                action: "get_job_categories",
                location: location
            }, 
            success: function(data) {
                // console.log(data);
                categorySelect.empty(); // empty all select options
                data.map(function(key, value) {
                    console.log(key.category);
                    categorySelect.append(`<option value="${key.category}">${key.category}</option>`);
                })
            },
            error: function(errorThrown) {
                // console.log(errorThrown);
            }
        });
    } else {
        $(this).parent().next().hide();
        categorySelect.empty(); // empty all select options
    }

  });
});
<?php 

function get_job_categories() {
    global $wpdb;
    $location = sanitize_text_field($_POST['location']);
    $stmt = $wpdb->prepare("SELECT DISTINCT category FROM jobs WHERE state = %s ORDER BY category ASC", $location);
    $results = $wpdb->get_results($stmt);
    echo json_encode($results);
    wp_die();
}

add_action( 'wp_ajax_get_job_categories', 'get_job_categories' );
add_action( 'wp_ajax_nopriv_get_job_categories', 'get_job_categories' );

?>
<form action="" method="POST">
  <div class="form-group">
    <label for="full_name<?php echo $counter; ?>">Full Name</label>
    <input type="text" name="full_name" id="full_name<?php echo $counter; ?>" class="form-control" required>
  </div>
  <div class="form-group">
    <label for="phone<?php echo $counter; ?>">Phone</label>
    <input type="tel" name="phone" id="phone<?php echo $counter; ?>" class="form-control" required>
  </div>
  <div class="form-group">
    <label for="email<?php echo $counter; ?>">Email</label>
    <input type="email" name="email" id="email<?php echo $counter; ?>" class="form-control" required>
  </div>
  <div class="form-group">
    <label for="location<?php echo $counter; ?>">Work Location</label>
    <select name="location" id="location<?php echo $counter; ?>" class="form-control" required>
        <option value="" selected readonly></option>
        <?php 
            $states = $wpdb->get_results("SELECT DISTINCT state FROM `jobs` ORDER BY state ASC");
            foreach($states as $job): 
        ?>
            <option value=""><?php echo $job->state; ?></option>
        <?php endforeach; ?>
    </select>
  </div>
  <div class="form-group" data-form-careers>
    <label for="type<?php echo $counter; ?>">Job Type</label>
    <select name="type" id="type<?php echo $counter; ?>" class="form-control" required>
        <option value="" selected readonly></option>
    </select>
  </div>
  <div class="form-group">
    <button name="submit" class="button button--red">
        Submit <?php echo file_get_contents($img_path . '/icons/arrow-circle.svg'); ?>
    </button>
  </div>
</form>