How to use ajax in WordPress step by step

Ajax is a ultimate JavaScript based technology for show the results without refreshing the page. Main reason use of ajax is more responsive and interactive web page from user point of view. For example when you fill any registration form then you need to show entered username already exist then you need ajax function for get the result without refresh the page. Today we learn how to use ajax in WordPress step by step. Let’s begin.

Add jQuery file in WordPress

Before use of ajax you need add jQuery CDN file for call ajax function. but good news is jQuery already a part of WordPress so you don’t need to add it in WordPress. Just add this code before use ajax. You can add this code in functions.php theme file OR in plugin file.

Now take a simple example for add code of ajax in theme’s footer.

In this example we need four parameters for use of ajax.

  • 1. Type: This could be “POST” OR “GET” Method for send the data to call back function.
  • 2. URL: This is url where we will send data for get response. In wordpress we should use admin_url(‘admin-ajax.php’) function for use of ajax.
  •  Data: In this parameter we defined the action of callback function and post or get values like username which one check in db exist or not.
  • success: With help of success we can get the data from ajax response. Here we can print data in html without refresh page.

Now third step is how to defined callback function in functions.php or in plugin file. Let see a example:


Here are two action hooks that allow user to handle Ajax request.
1. wp_ajax_(my_action) :- This hook use for logged in users.
2. wp_ajax_nopriv_(my_action) :- This hook use for not logged in users.

and then create my_action function where you can get posted values and return the data to ajax. I recommended wp_die() function for return exact value because many times exit() and die() functions not work.

Thanks for reading. Happy Learning…



Add a Comment

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