Advertisement
bowenac

Wordpress Using Ajax In Admin

Oct 28th, 2014
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
jQuery 1.99 KB | None | 0 0
  1. //  function at top of admin page backend
  2. add_action('wp_ajax_services_get_regions', 'services_get_regions');
  3. function services_get_regions(){
  4.     $group = $_GET['service_option_group'];
  5.     $regions_table = 'v_region';
  6.  
  7.     // Array to hold data
  8.     $bigArray = array();
  9.     // Variable to determine the select clause
  10.     $query = "";
  11.  
  12.     $query = "SELECT * FROM $regions_table WHERE `group` = $group ";
  13.     $regions = $wpdb->get_results($query);
  14.  
  15.     foreach($regions as $region) {
  16.         array_push($bigArray, $region);
  17.     }
  18.  
  19.     header( "Content-Type: application/json" );
  20.     echo json_encode($bigArray);
  21.  
  22.     //Don't forget to always exit in the ajax function.
  23.     exit();
  24. }
  25.  
  26. //Request on page that holds the page options for that tab in an include etc... <?php require_once('add_service.php'); ?>
  27. // watch for the region type selector to change, when it does update the region list
  28. jQuery('#new_service #service_option_group').on('change', function() {
  29.     // Ajax query to fetch the results
  30.     jQuery.ajax({
  31.         type: 'get',
  32.         url: ajaxurl,
  33.         data: {
  34.             action: 'services_get_regions',    
  35.             data: jQuery('#service_option_group').serialize()
  36.         },
  37.         dataType: 'json',
  38.         success: function(result) {
  39.             jQuery('#new_service #service_option_region').empty();
  40.  
  41.             // need to add the default option back in
  42.             var option = document.createElement('option');
  43.             var select = document.getElementById('service_option_region');
  44.             option.text = 'Select a Region'
  45.             option.value = -1;
  46.             select.appendChild(option);
  47.  
  48.             // Append on the events
  49.             for (var i = 0; i < result.length; i++) {
  50.  
  51.                 // create and append each element
  52.                 var option = document.createElement('option');
  53.  
  54.                 // result type will differ if its city or event
  55.                 option.text = result[i].title;
  56.                 option.value = result[i].id;
  57.  
  58.                 var select = document.getElementById('service_option_region');
  59.                 select.appendChild(option);
  60.             }
  61.         },
  62.         error: function(request, status, error) {
  63.             alert(request.responseText);
  64.         }
  65.     })
  66.  
  67. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement