Ajax in WordPress

ajax

Asynchronous JavaScript and XML or simply AJAX is a JavaScript and XML based programming technique that allows a web page to fetch or submit new information and present it without refreshing the web page. Its having “asynchronous” nature, which exactly means it can fetch or submit data without refreshing the page. This AJAX is working with simple Scripts and that are add on at the User Experience and User Interface. AJAX in WordPress is having the same nature and same work.

There are two major features of AJAX allow you to do the following:

  • Requests to the server without refreshing the page
  • Receive and work with data from the server

How does Ajax work?

Ajax technology is very straightforward to explain. Basically, the Web developer creates a link or button or some other type of user interface element on the page using the HTML and bind it to a JavaScript code. Once the user perform some event on the interface (i.e. clicks on the button or Change event or mouse scroll etc.) the JavaScript code get triggered and it sends some request to ask for data to a url on the web server. Once the request is submitted a action or line of code on the web server get execute and processes the request and perform the necessary action, once done it sends back  the data as the response. Usually the data which is being returned is in XML format, However that’s not our desired output. Once the data or response arrives in the browser, the JavaScript code receives AN “asynchronous” notification, so it is processed or displayed fittingly.

Ajax in WordPress

Ajax technology is being adopted by all types of websites — and WordPress isn’t any exception. Currently, the core of WordPress uses Ajax solely within the administration screens. as an example, Ajax is used for instant updates once you do comment moderation, and once you are adding and deleting things from lists like categories, blogroll, and posts; Ajax is additionally the technology behind the auto-save functionality on post and page editing screens. many themes and plugins additionally use Ajax; for example, some post rating plugins use Ajax to store the visitor’s rating within the database then show an updated average rating.

How Programing is done for AJAX in WordPress?

First of all we have to work on the HTML part. This will be our front end from where we are going to get the request and submit to our function here we are using the anchor tag for the request submission. we are not using any link instead we are just performing the on click event using JavaScript. So HTML code will be look alike something below.

<div class=""recentposts">
<ul>
</ul>
<div>
          <a href="#" class="load-more-data" data-load="4">LOAD MORE POST</a>
</div>
</div>

As we are done with the HTML its time to code for the JavaScript. As we are using the click event to pass the data we code in such way and using the $(‘someclassname’).click(function(e){}); we kept e to e.preventDefault(); so that the our window do not move. then we will fetch the data which we want to submit to the our action. Once we submit the data we will get the response and on success we can perform the desired change to our HTML using jQuery. We need to put the action name here in the ajax call so that the admin-ajax.php will able to understand that which function need to be executed.

/*AJAX CODE TO LOAD THE DATA OF THE */
jQuery(document).ready(function($) {
            // We'll pass this variable to the PHP function show_more_data
            $('.load-more-data').click(function(e) {
                e.preventDefault();
                var packages = $(this).parent().siblings('ul');

                $.ajax({
                    url: ajaxurl,
                    data: {
                        'action': 'load_more_taxonomy',
                        'loadeddata': noofloadedpackages,
                        'parentcategory': parentcategory,
                        'noofdata': noofdata,
                    },
                    success: function(data) {
                        // This outputs the result of the ajax request
                        packages.append(data);

                    },
                    error: function(errorThrown) {
                        console.log(errorThrown);
                    }
                });
            });

This is our final call time to create the action that will get the request and process and return the data. The name of the function can be different from the action we have kept in the JavaScript. But the action we are hooking must be same as the action. We are using two action to hook. once is ‘wp_ajax_our_function_name’ for authorized user and the second one is wp_ajax_nopriv_our_function_name for the unauthorized user. One our function is called we are checking that any $_REQUEST is submitted or not? and then we will fetch the submitted variable and process the data and return the value. The return data is in form of the HTML as we wanna display it at the front end.

function show_more_data()
	{
	// The $_REQUEST contains all the data sent via ajax
	if (isset($_REQUEST))
		{
                //Fetch the data passed by the ajax Request
		$loadeddata = $_REQUEST['someinputfieldname'];

		// Always die in functions echoing ajax content
		die();
		}
	}
//to handle AJAX requests made by authenticated users
add_action('wp_ajax_show_more_data', 'show_more_data');
//To handle AJAX requests on the front-end for unauthenticated users
add_action('wp_ajax_nopriv_show_more_data', 'show_more_data');

NOTE : you need to put the admin-ajax.php in for the both authorized and unauthorized user.

About Pashupatinath Mishra

Pashupatinath Mishra is Software Developer and our Fulltime blogger. He is having good knowledge on the Different Technologies and also having shareable knowledge on Nutrition, Science Topics, Travel and History.

Website

1 thought on “Ajax in WordPress

Leave a Reply

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

Time limit is exhausted. Please reload CAPTCHA.

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