How to make jQuery ajax (JSON) requests in WordPress

dataType
This should be set to ‘JSON’, indicating that we want the data returned in JSON format.

data
The data parameter represents the array of REQUEST (GET;POST) parameters that are passed to the remote URL (admin-ajax.php). So, any value we enter under the data parameter of the ajax call will be available as a REQUEST variable in admin-ajax.php. For instance, if we pass

ourVar: 'someValue'

as part of the ajax data parameter, it will be available at the remote URL (admin-ajax.php) as

$_REQUEST['ourVar']

This is part of the magic of making jQuery ajax calls. for our purposes we’ll pass three parameters within data:

  • ‘action’:’do_ajax’ (the action parameter is REQUIRED BY WORDPRESS in order to tell the remote URL which function to hook into. It doesn’t have to be called ‘do_ajax’, but it does have to match the action hook we will write just a bit later. This way, whenever an AJAX request has an action parameter that matches our WordPress action hook, it will do the function that we specify in that hook.)
  • ‘fn’:’get_latest_posts’ (this will be used to tell admin-ajax.php which server-side function we want it to run, once the ‘do_ajax’ process has begun)
  • ‘count’: 10

This way, admin-ajax.php will have two REQUEST variables available during this call,

$_REQUEST['fn']

and

$_REQUEST['count']

success
In the success parameter, we specify a success function that will run if our AJAX request is successful. Let’s create this function, but leave it blank for now. Creating the success handler will be one of the last steps.

error
Similar to the success function, the error parameter specifies a function to run if there is an AJAX error. We shouldn’t get any errors, but if we do, it’s useful to know what’s going on here.

Here’s the complete click handler with jQuery ajax call, in js.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
jQuery(document).ready(function(){
     jQuery('#json_click_handler').click(function(){
          doAjaxRequest();
     });
});
function doAjaxRequest(){
     // here is where the request will happen
     jQuery.ajax({
          data:{
               'action':'do_ajax',
               'fn':'get_latest_posts',
               'count':10
               },
          dataType: 'JSON',
          success:function(data){
                 // our handler function will go here
                 // this part is very important!
                 // it's what happens with the JSON data
                 // after it is fetched via AJAX!
                             },
          error: function(errorThrown){
               alert('error');
               console.log(errorThrown);
          }
     });
}

So, in functions.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
function our_ajax_function(){
   // the first part is a SWTICHBOARD that fires specific functions
   // according to the value of Query Var 'fn'
     switch($_REQUEST['fn']){
          case 'get_latest_posts':
               $output = ajax_get_latest_posts($_REQUEST['count']);
          break;
          default:
              $output = 'No function specified, check your jQuery.ajax() call';
          break;
     }
   // at this point, $output contains some sort of valuable data!
   // Now, convert $output to JSON and echo it to the browser
   // That way, we can recapture it with jQuery and run our success function
          $output=json_encode($output);
         if(is_array($output)){
        print_r($output);
         }
         else{
        echo $output;
         }
         die;
}

As you can see, this switchboard is now going to call one more function, ‘ajax_get_latest_posts’, because the ‘fn’ parameter of our jQuery.ajax() call matches the first case on the switch statement. So, we need to make this specific function, ‘ajax_get_latest_posts’, to, well, get the latest posts, and return the results as an array of PHP objects. So, also in functions.php

1
2
3
4
function ajax_get_latest_posts($count){
     $posts = get_posts('numberposts='.$count);
     return $posts;
}

So, running through the PHP code in ‘our_ajax_function’, this is what happens:

Advertisements
By Rz Rasel Posted in jQuery

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s