Menü schliessen
Created: May 29th 2015
Categories: IT Development,  Wordpress
Author: Marcus Fleuti

How to use Ajax in Wordpress

Tags:  Ajax,  JSON,  wordpress
Donation Section: Background
Monero Badge: QR-Code
Monero Badge: Logo Icon Donate with Monero Badge: Logo Text
82uymVXLkvVbB4c4JpTd1tYm1yj1cKPKR2wqmw3XF8YXKTmY7JrTriP4pVwp2EJYBnCFdXhLq4zfFA6ic7VAWCFX5wfQbCC

In this post we will explain how to use Ajax in WordPress manually, if you want to avoid usage of plugins. Step-by-step we will explain how to implement Ajax call, how to send data, handle that request in backend, return JSON result and finally parse that JSON into regular HTML. In this example we will send post ID to backend and return title and permalink of that post. In a same way we can return anything (content, featured image, even list of posts etc.).
First of all, let's say that we have default page.php template with basic structure like this:


<?php get_header();
  if(have_posts()):
    while (have_posts()): the_post(); ?>
      <?php echo get_the_ID(); ?>
    <?php endwhile;
  endif;
get_footer(); ?>

Now inside that PHP while loop we have just get_the_ID() PHP function that returns ID of current post. We will use that later. Now let's extend this code with Ajax call:

<?php get_header();
if(have_posts()):
  while (have_posts()): the_post(); ?>
    <script type="text/javascript">
      $(document).ready(function(){
        $.ajax({
          url: "<?php echo admin_url( 'admin-ajax.php' )?>",
          type:'POST',
          data: {
            "action" : "get_page_content",
            "ourpageid" : <?php echo get_the_ID(); ?>
          },
          dataType: "json",
          success:function(allresults){
            // do things here
          }
        });
      });
    </script>
    <div id="results"></div>
  <?php endwhile;
endif;
get_footer(); ?>

Let's analyze this code. We have added some jQuery code inside <script> tags and div with ID "results". Please make sure that you have included jQuery library inside your header.php file or whenever you want, but that library must be included. Also notice that this Ajax call will start on document ready but you can modify it to start on some other event (click, hover etc.).

  • Function ajax() have basic structure (you can see more about this function here).
  • Field "url" in this function will point always to the admin-ajax.php file which is part of every WP installation and we are printing path to that file like in code above.
  • Field "type" should be POST.
  • Field "data" represents variables or calls to some backend functions and can contain one action and more than one variable, but in our example we will use only "ourpageid" variable (we can call it whatever we want). Function that will be called with this Ajax request is called "get_page_content", but we can call it whatever we want.
  • Field "dataType" should be json because we want JSON to be returned via Ajax.
  • Function "success" will be started if call to Ajax is successful and we will later parse retrned JSON code inside that function and append it to div with ID "results".

That would be enough for now in frontend, let's see what need to be done in backend and how to handle those Ajax requests. We have pointed that url in Ajax call will call admin-ajax.php file and action would be "get_page_content". Now we must find way to conect those things somehow. Next code must be added to functions.php file:

<?php function implement_ajax_whatever() {
  if( (isset($_POST['ourpageid'])) ) {
    global $wpdb;
    $pageid = $_POST['ourpageid'];
    $getpagesbyid = $wpdb->get_results(
      "SELECT * FROM wp_posts WHERE ID = '$pageid'"
    );
    foreach ($getpagesbyid as $mypage) {
      $onePage = array();
      $onePage['mytitle'] = $mypage->post_title;
      $onePage['mypermalink'] = get_permalink($mypage->ID);
      $allPages[] = $onePage;
    }
    $getPages = json_encode($allPages);
  }
  echo $getPages;
  exit;
}
add_action('wp_ajax_get_page_content', 'implement_ajax_whatever');
add_action('wp_ajax_nopriv_get_page_content', 'implement_ajax_whatever'); ?>

Let's analyze this backend code.

  • First, we have function called "implement_ajax_whatever", and that function can be called whatever you want. But, that name you are using MUST be the same like in "add_action" at the bottom.
  • We are checking if variable "ourpageid" (remember that from frontend Ajax call?) have some value.
  • If yes, we need to set global variable wpdb.
  • Then we will pickup value of post variable "ourpageid" and save it to variable "pageid" (yes, the name is again your choice).
  • Now we create basic MySQL call to WP database. Here we can use MySQL call, but also all WP predefined functions like get_posts(), get_pages(), get_terms(), WP_query class. It's up to you.
  • Then we browse through all posts returned from DB (and currently saved in variable "getpagesbyid"). In this example we will get only one post because query asked for post with specific ID but in this way we can easily extend same code for more than one result. In foreach loop we create an array "onePage" and save title and permalink of this post (or of each post if there is more than one). Each array "onePage" will be added like element to one global array "allPages".
  • At the end we need to encode that array into JSON with json_encode() function, echo that JSON and exit function. When working with Ajax it's a good practice to manually exit, to prevent "data leaking" after results are returned.
  • Last thing in this backend code are two lines with "add_action". They are almost the same, one is for users that are logged to WP admin and second one for all other users. Also, really important part here is - if you look at code "wp_ajax_get_page_content" you will notice that it contains the same call like in forntend Ajax call ("action" : "get_page_content") and that is crucial part which is connecting frontend Ajax call, admin-ajax.php and this backend function which returns results.

Now we can back to frontend part of the code and finish it with code for parsing JSON results in success function, so the full frontend code looks like:

<?php get_header();
if(have_posts()):
  while (have_posts()): the_post(); ?>
    <script type="text/javascript">
      $(document).ready(function(){
        $.ajax({
          url: "<?php echo admin_url( 'admin-ajax.php' )?>",
          type:'POST',
          data: {
            "action" : "get_page_content",
            "ourpageid" : <?php echo get_the_ID(); ?>
          },
          dataType: "json",
          success:function(allresults){
             for (var i=0; i<=allresults.length; i++) {
               $('#results').append("<span>"+allresults[i].mytitle
               +"</span><br><span>"+allresults[i].mypermalink+"</span>");
             }
          }
        });
      });
    </script>
    <div id="results"></div>
  <?php endwhile;
endif;
get_footer(); ?>