ajax live search for post title

i m creating a AJAX live search to filter posts title in my wordpress theme.
As i write something in input it show all the post in result, Not filtering it to get custom post..

How to search live and find a post with AJAX??

Function.php

<?php 
add_action('wp_ajax_my_action' , 'data_fetch');
add_action('wp_ajax_nopriv_my_action','data_fetch');

function data_fetch(){
    $the_query = new WP_Query(array('post_per_page'=>5));
    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post(); ?>
            <h2><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h2>

        <?php endwhile;
        wp_reset_postdata();  
    endif;
    die();
}?>

Script:

<script>
function fetch(){

    $.post('<?php echo admin_url('admin-ajax.php'); ?>',{'action':'my_action'},
    function(response){
        $('#datafetch').append(response);
        console.log(result);
    });
}
</script>

HTML:

<input type="text" onkeyup="fetch()"></input>
    <div id="datafetch">
</div>

Solutions Collecting From Web of "ajax live search for post title"

Here is a working solution (tested as is)

The HTML (could be part of page content)

<input type="text" name="keyword" id="keyword" onkeyup="fetch()"></input>

<div id="datafetch">Search results will appear here</div>

The JavaScript ( goes to your theme’s functions.php )

// add the ajax fetch js
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) {
            jQuery('#datafetch').html( data );
        }
    });

}
</script>

<?php
}

And finally the AJAX call goes to your theme’s functions.php

// the ajax function
add_action('wp_ajax_data_fetch' , 'data_fetch');
add_action('wp_ajax_nopriv_data_fetch','data_fetch');
function data_fetch(){

    $the_query = new WP_Query( array( 'posts_per_page' => -1, 's' => esc_attr( $_POST['keyword'] ), 'post_type' => 'post' ) );
    if( $the_query->have_posts() ) :
        while( $the_query->have_posts() ): $the_query->the_post(); ?>

            <h2><a href="<?php echo esc_url( post_permalink() ); ?>"><?php the_title();?></a></h2>

        <?php endwhile;
        wp_reset_postdata();  
    endif;

    die();
}

i have been using this plugin :

ajax-search-pro-for-wordpress-live-search-plugin

it is the best plugin

and you can do this in 5 seconds using this.

i have used this plugin in my many Projects.