Search user metadata with checkboxes via ajax (almost working)

I have created an ajax search form following some tutorials online, it is working but not exactly how I need it to. Here is where I got the search from.

I have US states setup as a user meta field which is what I want to search against, then display the email addresses of the users in that state.

Right now the ajax search works but only if I search against post titles (using WP_Query). I have been unsuccessful in getting the ajax form to return any user meta search results via WP_Query.

Update:
I have come to find that WP_Query was wrong and am now using
WP_User_Query, thanks Milo.

Another question, how do I go about getting this to search for multiple strings (like Utah and California)?

Update: I figured out how to search for multiple parameters (at least it is
working for me), I added ‘meta_compare’ => ‘IN’ to the meta query array.

Once I can search for multiple strings could I just make regular checkboxes instead of an input text box or is it more involved than that? This is my last issue I need to resolve.

Updated checkbox code: I have tried changing my search like I found in other questions such as changing the name to an array and onkeyup
to onclick but it doesn’t work. It does something though as the
results say nothing found instead of the placeholder. As far asI could tell the function stays the same with just $_POST[‘keyword’].

<input type="checkbox" name="keyword[]" id="keyword" value="utah" onclick="fetch()" />

Update: I found a way to get my checkboxes passed via ajax and get used as a keyword using the code below, but I still have not figured
out how to get it to search more than one checkbox at a time (like
utah AND california).

My updated JS for searching (only searches one) checkbox:

 function updateTextArea() {         
     var allVals = [];
     $('#myform :checked').each(function() {
       allVals.push($(this).val());
     });
     //$('#datafetch').val(allVals);
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: $('#myform :checked').val() },
    success: function(data) {
        $('#datafetch').val($('#datafetch').val(data).replace("placeholder", data));
    }
    });
  }

Here is what I have working so far (code I started with):

add_action('wp_ajax_data_fetch', 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch', 'data_fetch');

function data_fetch() {

    $the_query = new WP_User_Query (array(
    'posts_per_page' => -1,
    's' => esc_attr($_POST['keyword']),
    'meta_query' => array(
        'relation' => 'OR',
            array(
                'key'     => 'state',
                'value'   => esc_attr($_POST['keyword']),
                'compare' => 'LIKE'
            ),
    ))
    );

    $str="";
    if ($the_query->have_posts()) {
        while ($the_query->have_posts()) {
            $the_query->the_post();
            // $str stuff is for adding a comma between results except for last
            $str .= $str?", 
":'';
            $str .= get_the_author_meta('user_email');
        }
        echo $str;
        wp_reset_postdata();  
    }
    die();
}

add_action('wp_footer', 'ajax_fetch');

function ajax_fetch() {
?>
<script type="text/javascript">
function fetch() {
    jQuery.ajax({
        url: '<?php echo admin_url('admin-ajax.php'); ?>',
        type: 'post',
        data: { action: 'data_fetch', keyword: jQuery('#keyword').val() },
  success: function(data) {
      // replaces text in an input text box
      $('#datafetch').val($('#datafetch').val(data).replace("placeholder", data));
  }
    });
}
</script>
<?php
}

Progress Update: I found a solution after doing more digging on WP_User_Query. I was trying to display the results in a loop like you
would when using WP_Query. But I found out you cannot use WP_User_Query in a
normal loop. This is the code bit I used to get the ajax search to
work by searching user meta fields.

function data_fetch() {
    //$name_array = preg_split("/[\s,]+/", $search_name);
    $args = array(
        //'role' => 'tour_author',
        'meta_key' => 'state',
        'meta_value' => esc_attr($_POST['keyword']),
        'meta_compare' => '='
    );

    $my_user_query = new WP_User_Query( $args );
    $editors = $my_user_query->get_results();
    $str="";

    if ( ! empty( $editors ) ) {
        foreach ( $editors as $editor ) {
            $str .= $str?", 
":'';
                $str .= $editor->user_email;
        }
        echo $str;
    } else {
        echo 'No editors found!';
    }
}

It works, it produces the results I need but with one issue. It produces a “0” at the end of the string. For example if I search for “Utah” it spits out the proper user but with the zero, so “[email protected]”. I have not been able to figure out why as of yet.

Update: Thanks to swissspidys comment I was able to get rid of the trailing zero. I needed to add die() to the end of the function

0

Leave a Comment