Back to Top

How to use Ajax in WordPress

To use ajax in wordpress

Recently I was working on to create ajax request in WordPress and I have created using callback of WordPress actions.

For calling a ajax request using WordPress default file, you need to include wp-admin/admin-ajax.php which is into wp-admin panel so you need to all that file into your theme to support ajax.

Here I Will explain you a tutorial to use an ajax call. In this tutorial, We will Show how ajax works in WordPress.

First of all, let’s see how to enqueue admin-ajax.php into your theme

Here ajax_url is a JavaScript variable used in WordPress to pass ajax requests to that uri.Using above code, you won’t have to use PHP to print out JavaScript code, which is non-cacheable and not feasible.It will generate HTML Code into tags like in below:

This is just for your information, don’t include above code into any file.

Now,in your JavaScript file, paste the following code of jQuery:

In the above jQuery code, we added the code at click event of a button but you can write on any event, you want.

Including the following line of codes, you can process the ajax request and display your data. you can add below code to your theme’s functions.php or a plugin file.

Mostly wp_ajax_nopriv prefix is used where as wp_ajax used for logged in users too.

That’s it.Now you can see yours ajax request in a browser. you are done it without any plugin. 🙂

You may also like:

To use multiple headers in WordPress
Voice Search in WordPress
To Reset the WordPress Loop

Thank you for reading.Feel free to share your thoughts! Don’t Forget to Follow us on Twitter or Subscribe us to Get the Latest Updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Most Popular Posts

How to clean HTML content in PHP?

Posted on 10 years ago

Bhumi

How to use Custom Query in Joomla?

Posted on 11 years ago

Bhumi