How to Implement Ajax to your WordPress Blog

AJAX or Asynchronous Javascript and XML, is a group of techniques used in web development with which you can load a new data on a part of the page without reloading the entire page.  Using AJAX, applications on the web can exchange data with the server without interfering with the existing web page. So let’s begin implementing ajax in WordPress.
Assume that your currently active theme is Twentyfourteen and you have created about four posts. First, visit the folder of your currently active theme and open functions.php file.
functionsphp

functions.php

Move to end of this file and write down the following code
1

1

Inside ‘add_action‘ write ‘wp_ajax_my_action‘ and the function name which is ‘data_fetch‘. Similarly, again inside ‘add_action‘ write ‘wp_ajax_nopriv_my_action‘ and ‘data_fetch‘.
Now write the code of the function ‘data_fetch’
data-fetch

data-fetch

Inside this you need to use ‘wp_query’ and use ‘posts_per_page‘ to fetch 10 posts. Run the loop using if condition and display the title and content. Make sure you call the die function.
So basically you are fetching 10 posts in reverse chronological order and we are displaying the title and content of it
Let’s move to the index.php and create a button which when clicked will make an Ajax call that displays the post.
create-button

create-button

js

denotes the path of the js folder

In WordPress when you implement Ajax you have to call a file/URL where you have to pass parameters to it. The URL basically resides in ‘wp_admin‘ folder which is admin-ajax.php.

ajaxphp

admin-ajax.php

After getting the data append it and place it into div providing an id called ‘datafetch’.

append

append

datafetch

data fetch

Run the complete code.

indexphp

index.php

Next, open firebug and click on the console tab, there is an AJAX call and you can see the response where the posts have been displayed.

open-firebug

open-firebug

displaying-the-posts

Displaying-the-posts

Christine

Christine

Author at onlineshouter
Christine writes for people who seek for knowledge about SEO, blogging, online marketing, gadgets and web apps.
Christine

Leave a Reply

Your email address will not be published.