0

I'm trying to create an ajax search form that gets WordPress posts if the search term is found within the post title. This is my PHP function:

function get_records_ajax($query) {

    $args = array(
        'post_type' => array('record'),
        'post_status' => array('publish'),
        'posts_per_page' => 999,
        'nopaging' => true,
        'meta_query'    => array(
            'key'       => 'title',
            'value'     => $query,
            'compare'   => 'IN',
        )
    );

    $ajaxposts = get_posts( $args );

    echo json_encode( $ajaxposts );

    exit;
}

And this is my jQuery function:

jQuery('.rrm_search_form').on('submit', function(e){
    e.preventDefault();
    let query = jQuery(this).find('.rrm_search_input').val();
    console.log('search submitted for ' + query);
    jQuery.ajax({
        type: 'POST',
        url: '<?php echo admin_url('admin-ajax.php');?>',
        dataType: "json",
        data: { action : `get_records_ajax(${query})` },
        success: function( response ) {
            jQuery.each( response, function( key, value ) {
                console.log( key, value );
            });
        },
        error: function(xhr, status, error) {
            var err = eval("(" + xhr.responseText + ")");
            console.log(err.Message);
        }
    });
});

I've tried lots of different syntax to try and pass the variable within the data action of my ajax call but nothing's working. Any ideas how I might be able to do this?

Ash
  • 49
  • 1
  • 1
  • 3
  • Have you registered your callback with [`wp_ajax_*`](https://stackoverflow.com/questions/48025825/wordpress-admin-ajax-php-400-bad-request)? – Chris Haas Nov 06 '20 at 18:07
  • Yes, I've registered it and it does work if you don't try and pass a variable i.e. `data: { action : 'get_records_ajax' }`, although it just returns all posts – Ash Nov 06 '20 at 19:27

1 Answers1

0

I assume your ajax URL is fine and loading in the website. Now all you have to modify your JS scripts and need to add hooks in PHP section. First in your JS script modify the data: line as follows:

data: { action : 'get_records_ajax', query: query },

Also You can add security check if you want. but leave it now.

Secondly, in your PHP file add the following code..

add_action( "wp_ajax_nopriv_get_records_ajax", 'get_records_ajax' );
add_action( "wp_ajax_get_records_ajax",        'get_records_ajax' );

and then in your get_records_ajax receive the query value

function get_records_ajax(){
  $query = sanitize_text_field($_POST['query']);

  //then your rest code


}

It will return all the post. Now you need to adjust your JS code in the success block :

success: function( response ) {
   console.log(response)
  //adjust here with your HTML dom elements 
}
SOS9GS
  • 362
  • 1
  • 7