Guest User

Untitled

a guest
Jul 19th, 2018
400
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. jQuery(document).ready(function($){
  2.     if (typeof acf == 'undefined') { return; }
  3.  
  4.       var acf_field = acf.getField('field_579376f522130');
  5.  
  6.       acf_field.on("change ready", function(e){
  7.  
  8.         // bail early if no ajax
  9.         if( !acf.get('ajax') ) return;
  10.  
  11.         // abort XHR if it's already running
  12.         if( this.request ) {
  13.           this.request.abort();
  14.         }
  15.  
  16.         // set the ajax action that's set up in php
  17.         var data  =  {
  18.             action: 'load_city_field_choices',
  19.             key_name: acf_field.val(); //The key_name needs to be the name of the parameter in your action
  20.         }
  21.  
  22.         this.request = $.ajax({
  23.           url:    acf.get('ajaxurl'),  // ajax url, acf already sets this
  24.           data:    acf.prepareForAjax(data), // another included acf function
  25.           type:    'post', // posted values, look at $_POST in your php ajax action function
  26.           dataType:  'json', // how we want the date returned
  27.           success: function( json ){
  28.             // get the field we want to populate
  29.             var $select = $('.acf-field-5793770922131 select');
  30.             // this stores the currenlty selected value in that field
  31.             // so that we can mark it as selected, this is important when loading
  32.             // and exsiting post
  33.             var $selected = $select.val();
  34.             // clear all of the exsiting options from the field
  35.             $select.empty();
  36.             // rebuild the child select field
  37.             $select.append('<option data-i="" selected="selected" value="">- Select -</option>');
  38.             var count = json.length;
  39.             for (i=0; i<count; i++) {
  40.               var $item = '<option value="'+json[i]['value']+'"'
  41.               if ($selected == json[i]['value']) {
  42.                 $item += ' selected="selected"';
  43.               }
  44.               $item += '>'+json[i]['label']+'</option>';
  45.               $select.append($item);
  46.             }
  47.           }
  48.         }); // end ajax
  49.  
  50.       });
  51.  
  52.       // trigger the ready action to load the field
  53.       // this is important for existing posts
  54.       $('#acf-field_579376f522130').trigger('ready');
  55.  
  56.   });
Advertisement
Add Comment
Please, Sign In to add comment