Creating an auto result search bar

Then “autoSearch.php” has this code:

If that’s all there is, no wonder you get an error – WP isn’t even loaded!

Add this to your functions.php

isset( $_POST['autoSearch'] ) && add_action( 'after_setup_theme', 'wpse_60353_autosearch' );
function wpse_60353_autosearch()
{
    // The autoSearch.php code you posted in your question

    exit; // All done, stop WP continuing
}

Now just use the main URL for your AJAX request. The function will intercept the default WordPress runtime & return your data as expected.

$.post( "<?php echo esc_js( site_url() ) ?>" ...

Using this technique means you’ll have access to all of WP inside wpse_60353_autosearch, without having to point to an external file & dirtily loading WP with something like require '../../../wp-load.php (or similar).


Update: Firstly, I would strongly advise to use something like typewatch – using onkeyup will fire a request far too often for what you need; it’ll annoy the user not to mention overload the server.

Secondly, I’ve noticed an error in your query:

$args = array( 'post__in='.$mypostids ); // This concats your IDs array to a string
$args = array( 'post__in' => $mypostids ); // See the difference?

In fact, I would rewrite it to use the initial result – saves querying & should lighten things up:

isset( $_POST['autoSearch'] ) && add_action( 'after_setup_theme', 'wpse_60353_autosearch' );
function wpse_60353_autosearch()
{
    global $wpdb;

    $query = like_escape( $_POST['autoSearch'] );
    $posts = $wpdb->get_results( $wpdb->prepare( "
        SELECT * FROM $wpdb->posts
        WHERE
            post_status="publish" AND
            post_title LIKE %s AND
            post_type IN ( 'post', 'page' )
        ORDER BY
            post_date DESC
        LIMIT 5",

        "%$query%"
    ));

    // update_post_caches( &$posts, $post_type, $update_term_cache, $update_meta_cache )
    update_post_caches( $posts, 'post', false, true );

    $titles = array();
    foreach ( $posts as $post )
        $titles[] = get_the_title( $post->ID );

    header( 'Content-Type: application/json; charset=UTF-8' );
    echo json_encode( array( 'everything' => implode( '<br />', $titles ) ) );
    exit;
}

And for your JS:

function autoSearch( link )
{
    var $results = $( "#searchResults" ).width( $( "#searchArea" ).width() ), s = $( "#searchField" ).val();
    if ( s != "" ) {
        $.post( link, { autoSearch: s }, function ( data ) {
            $results.show().html( data.everything );
        }, "json" );
    } else {
        $results.hide();
    }
}

Note that I have tested this code on my own install & can confirm it functions as expected: typing a search term displays a maximum of 5 found titles, otherwise the results div is hidden if no results.