I'm trying to output the results of the SQL statement into the select#input_6_26 option. The code is running and the Ajax request is properly requesting the PHP function, however it's only outputting the word 'Array' and not the actual results. I think I'm needing to ask how to set the results to an array and properly output those. Any help would be appreciated!

Setting Ajax shortcode for URL:

function add_ajaxurl_cdata_to_front(){ ?>
<script type="text/javascript"> //<![CDATA[
    ajaxurl = '<?php echo admin_url( 'admin-ajax.php'); ?>';
//]]> </script>
<?php }
add_action( 'wp_head', 'add_ajaxurl_cdata_to_front', 1);

add_action( 'wp_footer', 'add_js_to_wp_footer' );
function add_js_to_wp_footer() { ?>

Ajax Call:

   <script type="text/javascript">
   jQuery("#field_6_17 select").on('change', function() {

    var product_line = jQuery(this).val();

    jQuery.ajax({
        type: 'POST',
        url: ajaxurl,
        data: {
          "action": "view_site_description",
          first_name : 'John',           // PHP: $_POST['first_name']
          last_name  : 'Cena',
        }, success: function(data){
          jQuery('select#input_6_26 option').html(data);
        }
    });
     return false;
    });
    </script>
    <?php }

PHP Function:

function view_site_description(){
global $wpdb;
$choices = [];

$termId = $wpdb->get_results("SELECT term_id FROM wp_terms WHERE name = 'Baffles'");

  foreach($termId as $termIds) {

    $objectId = $wpdb->get_results("SELECT object_id FROM wp_term_relationships WHERE term_taxonomy_id = $termIds->term_id");

      foreach($objectId as $objectIds) {

        $postId = $wpdb->get_results("SELECT post_title FROM wp_posts WHERE id = $objectIds->object_id AND post_status = 'publish'");

          foreach($postId as $postIds) {

            $choices = array("text" => $postIds->post_title, "value" => $postIds->post_title);
          }
      }
  }

  echo $choices;
  die();
  }
  add_action( 'wp_ajax_view_site_description', 'view_site_description' );
  add_action( 'wp_ajax_nopriv_view_site_description', 'view_site_description' );
  • to transform the array in JSON and send it, you can use wp_send_json($choices); – mmm Jan 10 at 17:04
  • That results in echoing out blank results in the select element. – Seth Spivey Jan 10 at 17:12

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Browse other questions tagged or ask your own question.