Title: Dropdown lists AJAX
Last modified: November 28, 2017

---

# Dropdown lists AJAX

 *  [jamiesw](https://wordpress.org/support/users/jamiesw/)
 * (@jamiesw)
 * [8 years, 5 months ago](https://wordpress.org/support/topic/dropdown-lists-ajax/)
 * I am developing a custom plugin that has a dropdownlist that gets it value & 
   text from the Database. I then have another dropdownlist that needs to be populated
   based on the previous dropdown selected value.
 * Here is the code i have for the AJAX, but doesnt seem to be working. My jquery
   code is in a separate js file….
    /plugindir/customplugin/js/jsscript.js
 *     ```
       jQuery(document).ready(function() {
       jQuery('#ddlSchool').change(function(){
       var school=jQuery('#ddlSchool').val();
       jQuery('#ddlResVisit').empty(); //remove all existing options
       jQuery.ajax({
       			type: 'POST',
              dataType: 'json',
                   url: residential_visits.ajaxurl,
                   data: {
               	'action' : 'residential_visits',
       	        'school' : school
                       },
       	complete: function( response ) {
       		console.log(response );
       		alert(response.responseText);
                );
       	}
             });
          });
       });
       ```
   
 * Custom Plugin File that has my php and html
 *     ```
       <?php
       //Load CSS and Javascript Files
       wp_register_style('my_styles', plugins_url('css/styles.css', __FILE__));
       wp_enqueue_style('my_styles');
       wp_enqueue_script( 'jquery' );
       wp_register_script('ajax-script', plugins_url('js/jsscripts.js', __FILE__), array('jquery'),'1.1');
       wp_enqueue_script('ajax-script');
       wp_localize_script( 'ajax-script', 'residential_visits', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
        // THE AJAX ADD ACTIONS
       add_action( 'wp_ajax_residential_visits', 'residential_visits');
       add_action( 'wp_ajax_nopriv_residential_visits', 'residential_visits');
   
       //Function to be called from AJAX SCRIPT
       function residential_visits() {
       ob_clean();
       $school = $_POST['ddlSchool'];
       global $wpdb;
   
       $result = get_results("select id, group_name from wp_pods_residential_visits where school='$school'");
       $main = array('data'=>$result);
       echo json_encode($main);
           // Don't forget to stop execution afterward.
       wp_die();
       }
       ```
   
 * And finally the code from my first dropdownlist
 *     ```
       <?php 
       //get list of schools
       global $wpdb;
       $schools = $wpdb->get_results("Select abbr_code, school_name from wp_pods_schools order by school_name;");
       ?>
       <label for"ddlSchools">School Attending:</label>
       <select name="ddlSchool" id="ddlSchool">
       <?php
       foreach ($schools as $school){
       ?>
       <option value="<?php echo $school->abbr_code ?>"><?php echo $school->school_name ?></option>
        <?php
       }
         ?>
       </select>
       ```
   
 * Any help would be greatly appreciated as i cannot see why it isnt working.
 * thanks
    Jamie
    -  This topic was modified 8 years, 5 months ago by [bcworkz](https://wordpress.org/support/users/bcworkz/).
      Reason: Code fixed - bbcode doesn't work

Viewing 4 replies - 1 through 4 (of 4 total)

 *  Moderator [bcworkz](https://wordpress.org/support/users/bcworkz/)
 * (@bcworkz)
 * [8 years, 5 months ago](https://wordpress.org/support/topic/dropdown-lists-ajax/#post-9731195)
 * In function residential_visits(), is get_results() declared anywhere in your 
   code? It’s not a standard WP or PHP function. Maybe you meant it to be like this:`
   $result = $wpdb->get_results('your SQL here');`?
 * FYI, bbcode like `[code]` doesn't work here. Either use backticks or the code
   button. The attempt at good formatting is appreciated though 🙂
 *  Thread Starter [jamiesw](https://wordpress.org/support/users/jamiesw/)
 * (@jamiesw)
 * [8 years, 5 months ago](https://wordpress.org/support/topic/dropdown-lists-ajax/#post-9731271)
 * sorry yes it is meant to be `$result = $wpdb->get_results('your SQL here');` 
   but even updating that hasn’t made a difference, any where else i have missed
   a bit out or misspelled something?
    many thanks Jamie
 *  Thread Starter [jamiesw](https://wordpress.org/support/users/jamiesw/)
 * (@jamiesw)
 * [8 years, 5 months ago](https://wordpress.org/support/topic/dropdown-lists-ajax/#post-9733584)
 * In my console output i am now getting a 400 Bad Request (VM2647:1 POST [http://my.desktopserver.dev/wp-admin/admin-ajax.php](http://my.desktopserver.dev/wp-admin/admin-ajax.php)
   400 (Bad Request))
 * Calling my php function directly on the page works and echo’s out the correct
   info on the page, so i know the function works.
    also in my jsscript.js i did
   an `alert(residential_visits.ajaxurl);` and it shows the admin-ajax.php url as
   it is meant to.
 * JSSCRIPTS FILE:
 *     ```
       jQuery(document).ready(function() {
       jQuery('#ddlSchool').change(function(){
       //var st=$('#category option:selected').text();
       var school=jQuery('#ddlSchool').val();
       jQuery('#ddlResVisit').empty(); //remove all existing options
       jQuery.ajax({
       			type: 'POST',
       			dataType: 'json',
       			contentType: "application/json",
       			url: residential_visits.ajaxurl,
       			data: {
       				'action' : 'residential_visits',
       				'school' : school
       			},
       			complete: function( response ) {
       				console.log(response);
       				//alert(response.responseJSON.body);				
       			}
       		});
       	});
       });
       ```
   
 * PHP file in my custom plugin folder (this php file also creates the content used
   on the page as a shortcode, I dont know if this make a difference? Does my PHP
   function need to be elsewhere for it to be seen by the ajax handler?
 *     ```
       <?php
       // Registration form
       //Load CSS and Javascript Files
       wp_register_style('reg_styles', plugins_url('css/styles.css', __FILE__));
       wp_enqueue_style('reg_styles');
   
       wp_register_script('ajax-script', plugins_url('js/jsscripts.js', __FILE__), array('jquery'),'1.1');
       wp_enqueue_script('ajax-script');
       wp_localize_script( 'ajax-script', 'residential_visits', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
        // THE AJAX ADD ACTIONS
       add_action( 'wp_ajax_residential_visits', 'residential_visits');
       add_action( 'wp_ajax_nopriv_residential_visits', 'residential_visits');
       //residential_visits(); -WHEN ENABLED IT SHOWS THE DATA SO IT WORKS
   
       function residential_visits() {
       ob_clean();
       // Handle request then generate response using WP_Ajax_Response
       global $wpdb;
       $result = $wpdb->get_results("select id, group_name from wp_pods_residential_visits ");
       //$main = array('data'=>$result);
       echo json_encode($result);
       // Don't forget to stop execution afterward.
       wp_die();
       }
       }
       if (!empty($_POST)){
       //Pass Form Data to Save Function
       saveRegData($_POST);
       echo "<h2>Thank you for submitting the registration information.</h2>";
       }
       else{
       //Display Registration Form
       ?>
       <form method="post" name="frmVisit" id="frmVisit">
       <table id="tblRegistration" name="tblRegistration" class="tblRegForm">
       <!-- Other form Fields -->
       <tr>
       <td colspan="2"><h3>School Details</h3></td>
       </tr>
       <tr>
       <td colspan="2">
       <?php 
       // Get list of schools
       global $wpdb;
       $schools = $wpdb->get_results("Select abbr_code, school_name from wp_pods_schools order by school_name;");
       ?>
       <label for"ddlSchools">School Attending:</label>
       <select name="ddlSchool" id="ddlSchool">
       <?php
       foreach ($schools as $school){
       ?>
       <option value="<?php echo $school->abbr_code ?>"><?php echo $school->school_name ?></option>
       <?php } ?>
       </select>
   
       <select id="ddlResVisit" name="ddlResVisit">
       </select>
          <!-- Rest of HTML, PHP to save data etc -->
       ```
   
 * Any clues?
 * Jamie
 *  Moderator [bcworkz](https://wordpress.org/support/users/bcworkz/)
 * (@bcworkz)
 * [8 years, 5 months ago](https://wordpress.org/support/topic/dropdown-lists-ajax/#post-9734743)
 * If your function is available in normal WP code, such as on a template, it will
   be available to Ajax handlers, assuming the Ajax request is sent through admin-
   ajax.php.
 * I think the problem is your contentType header. The data sent is not JSON, it’s
   plain text. Er, well, kind of. You pass a plain object as data: and jQuery automatically
   converts it to a plain data string. Thus when the server gets the data it’s plain
   text. Try passing `text/plain` or the default `application/x-www-form-urlencoded`
   instead. Note that dataType json is fine, that’s what you want back.

Viewing 4 replies - 1 through 4 (of 4 total)

The topic ‘Dropdown lists AJAX’ is closed to new replies.

 * In: [Developing with WordPress](https://wordpress.org/support/forum/wp-advanced/)
 * 4 replies
 * 2 participants
 * Last reply from: [bcworkz](https://wordpress.org/support/users/bcworkz/)
 * Last activity: [8 years, 5 months ago](https://wordpress.org/support/topic/dropdown-lists-ajax/#post-9734743)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
