How to use AJAX in WordPress theme

by in , on

Now these days AJAX become more popular to create dynamic, user-friendly and responsive websites. AJAX is the technology to send and receive data with reload the page in web browser. One of the great example you can see in Google DOCS, that saving your work in few minutes or you can see instant image upload.

What is AJAX?

If still you are not familiar with AJAX then we suggest you to read about AJAX on Wikipedia. Or you can use AJAX with jQuery, one of the most popular JavaScript Library. AJAX is the combination of HTML, CSS and JavaScript code that helped you to send data to the particular file and receive the response from that file without refreshing the browser or page.

How Ajax Works With WordPress

If you are familiar with WordPress then hopefully you noticed that when we creating a page or post in WordPress then the create page or post automatically saving on the draft, or WordPress Uploader to upload and re-size the images that’s also a known example of AJAX and jQuery. Basically AJAX already used in WordPress back end. Every AJAX request call to the admin-ajax.php file that is located in wp-admin folder. Every request sending there data (GETorPOSTmethod) that calledaction.

The code in admin-ajax.php make two hooks, one is wp_ajax_my_action and the second is wp_ajax_nopriv_my_action wheremy_actionis the value ofGETorPOSTvariable. First hook means the function will fire if a user is logged in, and second function fire when the user is logged-out.

Implementing AJAX in WordPress

There are many ways to implementing AJAX into your theme, but we implement it in WordPress-style, make sure that before your own AJAX script you should have to add jQuery Library, take a look on the below codes:

 

WordPress including JavaScript file through this way. First we register our file with wp_register_script() so that the WordPress knows about this file. As you see, we didn’t give any url of jQuery file in our codes because WordPress has a collection of registerd scripts, we just have to call that registered script to implement into your theme.

Now we have to implement AJAX request in our JavaScript file that we inserted into ourmy_enqueue_script()function.

 

In the above codes you have to collect some data that you want to send through AJAX then pass it tomy_ajax_action()function that you have to defined in your functions.php file that returns back the result in JSON format.

Hope you all enjoying this post, it would be great to hear from for any suggestion and complement through comment section.