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.jsjQuery(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
Viewing 4 replies - 1 through 4 (of 4 total)
Viewing 4 replies - 1 through 4 (of 4 total)
The topic ‘Dropdown lists AJAX’ is closed to new replies.