Using AJAX For Smooth Loading of Search Results in WordPress Site

AJAX (also referred to as Asynchronous JavaScript and XML) enables developers to build streamlined web applications. The biggest advantage of AJAX is that it allows user’s to interact with the web pages and applications asynchronously, without communicating with the server. Put it simply, user can fetch new data from the server without reloading the page. AJAX has taken the web world by storm and is adopted by all kind of websites because of its responsiveness and flexibility, and WordPress is no exception. WordPress is compatible with AJAX, allowing you to integrate AJAX functionality into your site without much fuss.

In this post we’ll talk about how AJAX is used in WordPress, and will provide you an example as how you can load search results by using AJAX in your WP site.AJAX For Smooth Loading of Search Results in WordPress Site

How to Use AJAX in WordPress?

AJAX is self-sufficient, and doesn’t require a framework such as WordPress, in fact, you can implement it the way you deem perfect. However, combining both WordPress and AJAX technologies can help in making your WordPress powered site highly interactive for users.

To demonstrate using AJAX with WP, let’s look at an example that’s divided into three steps. We’ll begin with creating a custom solution to make use of AJAX in WordPress. In the second step, we’ll create a button that will remain in the display mode until it’s not being clicked by the user, and if the button is clicked users will see a message “already clicked”.

Lets Get Started With Custom Implementation

We’ll first have to find a way to know whether a user has hit the button or not. In case the user clicks the button, we’ll create a user meta named “clicked_link” that is assigned a value of “Yes”. The following snippet verifies this concept:

<?php
function has_user_clicked_button() {
    if ('yes' == get_user_meta(get_current_user_id(), 'clicked_button', true)) {
        return true;
    }
    return false;
}

Next, we’ll create a user interface. As discussed previously, the button will only be visible to users (logged-in users) until they haven’t clicked it. But in case a user hit the button, the message “Already clicked” will show up:

<?php
if (is_user_logged_in()) {
    if (has_user_clicked_button()) {        
        echo "alreadyclicked";
    } else {
        echo "<a id='button' href='?button_click=true'>Click On This</a>";
    }
}

If the button is clicked by the user, then the page gets reloaded via the “button_click” query string. We’ll use this value as input, so as to set the user meta:

<?php
add_action('init', 'user_clicked');

function user_clicked() {
    if (is_user_logged_in() && !empty($_GET['button_click']) && $_GET['button_click'] == 'true') {
        update_user_meta(get_current_user_id(), 'clicked_button', 'yes');
    }
}

Note: There’s an issue with this method. The button will be visible to the logged-in users who haven’t hit the button yet. And when you click the button, you’ll be re-directed to the page that was already opened prior to when the button was clicked and that page gets reloaded.

Setting Up AJAX Foundations Without AJAX

Before, using AJAX as a whole, let’s first set up AJAX foundations. For this we’ll have to route our actions using the admin-ajax.php file. This will result in making some changes to our previously written code for our button:

<?php
if (is_user_logged_in()) {
    if (has_user_clicked_button()) {
        echo "already clicked";
    } else {
        echo "<a id='button' href='" . admin_url('admin-ajax.php?action=button_click') . "'>Click here now</a>";
    }
}

Looking at the above snippet, you can see that the button’s URL has changed, which now points to the admin-ajax.php file that can be found in the WordPress admin directory. Besides this, the button_click represents an action parameter. Let us now use actions for the events.

<?php
add_action('wp_ajax_button_click', 'user_clicked');

function user_clicked() {
    update_user_meta(get_current_user_id(), 'clicked_button', 'yes');
    wp_redirect($_SERVER['HTTP_REFERER']);
    exit();
}

As you can see, in the above code the user_clicked() function is re-written to make the changes possible. As a result, we won’t have to inspect whether the user is logged-in or not, instead this will be handled by the wp_ajax_button_click hook.

Full Implementation of AJAX

Now for implementation of AJAX in its entirety we’ll use the foundations that have been built in the aforementioned example. In order to handle the button click event, we’ll write some Javascript code.

jQuery(document).on('click', '#button', function() {
    var button = jQuery(this);
    var url = button.attr('href');
    jQuery.ajax({
        type: 'post',
        url: url,
        data: {
            action: 'user_clicked'
        },
        success: function(response) {
            if (response === 'ok') {
                button.fadeOut(function() {
                    button.replaceWith('already clicked');
                })
            }
        }
    });
    return false;
})

The code will help in detecting the button click, and then a request is sent to the admin-ajax.php file using the ajax() function. The type of request used here is assigned the value post. Furthermore, the data object elements are moved as $_POST array members. In addition, a success function is added to substitute the button with the text “already clicked” except that the response must be “OK.”

This request is quite similar to the one where we directly routed our users to the file. Here’s we’re defining an action that function in the manner it was designed for.

<?php
add_action('wp_ajax_button_click', 'user_clicked');

function user_clicked() {
    update_user_meta(get_current_user_id(), 'clicked_button', 'yes');
    echo 'ok';
    die();
}

Finally, the users are spared from redirecting the page since they no longer need to leave the page. It is important to display OK and also we’ll have to use die(). In essence, when the button is clicked by a user things are handled asynchronously.

Load Your Site’s Search Results With AJAX

Here we’ll look an example that use AJAX on WordPress theme search page to load search results. We’ll first have to create a child theme. In addition we have to consider several aspects, such as:

Enqueueing JavaScript File

In order to integrate JS functionality, we will need to enqueue the JavaScript file. And we’ll have to be sure that the script we have written is loaded on the search page only.

<?php
function ajax_search_enqueues() {
    if (is_search()) {        
        wp_enqueue_script('ajax - search', get_stylesheet_directory_uri() . ' / js / ajax - search . js', array('jquery'), '1.0.0', true);
        wp_localize_script('ajax - search', 'myAjax', array('ajaxurl' => admin_url('admin - ajax . php')));
        wp_enqueue_style('ajax - search', get_stylesheet_directory_uri() . ' / css / ajax - search . css');
    }
}

add_action('wp_enqueue_scripts', 'ajax_search_enqueues');

In the above code, wp_localize_script() function is used to provide access to the admin-ajax.php file location. Additionally, this function lets you add language support to the scripts.

What’s more, as you can see in the code, a CSS file is also enqueued. The CSS file code will be added in the stylesheet of our child theme’s.

Interrupting Searches To Produce New Results

In this step we’ll discuss about how we can stop searches, and pass the search queries to the newly created custom script. This will help us in acquiring new results. Our Javascript will look something like as follows:

jQuery(document).on('submit', '#search-container form', function() {
    var $form = jQuery(this);
    var $input = $form.find('input[name = "s"]');
    var query = $input.val();
    var $content = jQuery('# content')
    jQuery.ajax({
        type: 'post',
        url: myAjax.ajaxurl,
        data: {
            action: 'load_search_results',
            query: query
        },
        beforeSend: function() {
            $input.prop('disabled', true);
            $content.addClass('loading');
        },
        success: function(response) {
            $input.prop('disabled', false);
            $content.removeClass('loading');
            $content.html(response);
        }
    });
    return false;
})

In the code snippet above, the beforeSend event is used to append loading class to the element “content” and for deactivating the input. This will ensure that the user gets some feedback, and also ascertain that multiple requests are not being sent because of multiple queries. Let’s now look at the CSS that will give you an idea of how loading can be handled:

#content.loading > * {
    opacity: 0.2;
}
#content.loading: before {
    content: “Loading New Posts”;
    padding: 21px;
    background: #000;

    color: # fff;
    width: 100 % ;
    box - sizing: border - box;
}

The Server Side

In the above example, we used ‘load_search_results’ in the JavaScript to specify the intended action. We’ll use the same for other actions that we’ll create in the future. On the server side, we will be running the load_search_results action for both logged-in as well as logged-out users, using wp_ajax and wp_ajax_nopriv respectively.

A custom WordPress query will be created, so that we can reuse the same code of our theme “search.php” file:

<?php
add_action( 'wp_ajax_load_search_results', 'load_search_results' );

add_action( 'wp_ajax_nopriv_load_search_results', 'load_search_results' );

function load_search_results() {
    $query = $_POST['query'];
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        's' => $query
    );

    $search = new WP_Query( $args );
    ob_start();

    if ( $search->have_posts() ) :
        ?>
        <header class="page-header">
            <h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'theme_name' ), get_search_query() ); ?></h1>
        </header>
        <?php
        while ( $search->have_posts() ) : $search->the_post();
            get_template_part( 'content', get_post_format() );
        endwhile;

        theme_name_paging_nav();

    else :
        get_template_part( 'content', 'none' );
    endif;

    $content = ob_get_clean();

    echo $content;

    die();
}

Conclusion :

Whether you want to make a little improvements to the user interface or want to optimize performance of your web applications, AJAX proves to be a productive tool in the WordPress toolkit. Reading this post will hopefully help you understand how you can use AJAX to load search results on your WordPress theme search page.

In case you want to utilize AJAX functionality, you can even use AJAX-related plugins available in the WP plugins repository.

Written by Amy Brown

Amy is a WordPress developer by profession and works for WordPrax Ltd, a Custom WordPress Development Services provider with a global reach. Amy loves innovative approach to web development and has a strong inclination for a suite of creative endeavors. Blogging meanwhile is a new found hobby for Amy.

Website: http://www.wordprax.com/

2 thoughts on “Using AJAX For Smooth Loading of Search Results in WordPress Site

  1. It's in reality a great and helpful piece of info. I am satisfied that you shared this helpful information with us.

    Please stay us up to date like this. Thank you for sharing.

Comments are closed.