Adding AJAX to WordPress - Developer Guide

Adding AJAX to WordPress – Developer Guide

AJAX give app like feel to a website. With AJAX a page’s content is updated without page refresh. Ajax is the art of exchanging data with a server, and updating parts of a web page without reloading.

What Is AJAX?

AJAX stands for Asynchronous JavaScript and XML. In simple words, we can say AJAX update web asynchronously. Generally all request made from a webpage are synchronous. Means, when a request is sent, next request can be made only if previous request is complete. While an asynchronous request don’t disturb next request call.

If you don’t aware of AJAX you can follow How To Make AJAX form tutorial. AJAX retrieve information from server and update particular part of the webpage.

Adding AJAX in WordPress Site

Adding AJAX in WordPress site is quite simple. This tutorial is for WordPress developer. I don’t suggest any plugin for the same. As such plugin only provide a limited functionalities.



Adding AJAX JavaScript to WordPress

To update a part of webpage we need to call a event using JS. Event can be any event as per requirement. Here I take click event of a button.

$("#submit").click(function(){
    // AJAX Code To Submit Form.
    $.ajax({
        type: "POST",
        url: "<?php echo admin_url( 'admin-ajax.php' ); ?>", //WordPress ajax page URL
        data: {
            'action' => 'get_next_posts_title', //use in wp_ajax function
            'pageNum' => '3' //can be dynamic
        },
        success: function(result){
            $('#target_div').html(result);
        }
    });
});

It’s a simple JS code for onclick, we show next posts title in a target div (with id = target_div). Code is simple to understand, In WordPress all ajax request is sent to admin-ajax.php page. Which URL can be get by admin_url( ‘admin-ajax.php’ ).

How to Add JS to WordPress?

Adding this code snippet to WordPress page is quite simple. With following code snippet you can add this to your site. I recommended to use a child theme for code update.

add_action('wp_footer', 'ds_add_ajax_script');
function ds_add_ajax_script(){
?>
<script>
    $("#submit").click(function(){
    // AJAX Code To Submit Form.
    $.ajax({
        type: "POST",
        url: "<?php echo admin_url( 'admin-ajax.php' ); ?>",
        data: {
            'action' => 'get_next_posts',
            'pageNum' => '3'
        },
        cache: false,
        success: function(result){
            $('#target_div').html(result);
        }
    });
});
</script>
<?php 
}

If in console you found $ not defined error, then replace $ with jQuery. This is due to your theme using jQuery.

Adding PHP code to get Response

add_action( 'wp_ajax_get_next_posts', 'ds_get_next_posts_func' );
add_action( 'wp_ajax_nopriv_get_next_posts', 'ds_get_next_posts_func' ); //add if ajax is call from front-end

function ds_get_next_posts_func(){
    //code for getting posts of page 3
    $args = array(
        'post_type' => 'post',
        'post_status' => 'publish',
        'paged' => $_POST['pageNum']
    );
    $ds_posts = new WP_Query($args);
    if($ds_posts->have_posts()){
        while($ds_posts->have_posts()){
            $ds_posts->the_post();
            echo '<h3>'.get_the_title().'</h3>';
        }
    }else {
        echo 'Sorry No Post Found';
    }
    die();
}

Although code is self explained still I explain it by line number.

  • Line 1: WordPress use wp_ajax_ followed by action use in ajax js as hook to call ajax. Any callback function attached to it, will call whenever ajax is called.
  • Line 2: If request is made from front-end then wp_ajax_nopriv_ followed by ajax action hook is use.
  • Any thing print here will be return as response in AJAX js.
  • Line 20: Die() is use to tell request that we get the response, no need to use wp-ajax.php file any more for this request. If you don’t add it, it behave weird.

Although this is a simple tutorial but it will helps a lot. In next article I will write about how to handle advanced AJAX in WordPress. Please comment if you have any suggestion and issue. Share if you like it.

How useful was this post?

Click on a star to rate it!

Average rating 5 / 5. Vote count: 2

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Share the Article

About author
Darshan Saroya

Darshan Saroya

A passionate WordPress Theme Developer. I love to create clean and modern themes, using the power of WordPress. Here I provide the tutorials related to WordPress Development, Core PHP and HTML.