How to use ajax in WordPress – on frontend and admin side

Ajax ( Asynchronous JavaScript and XML ) allows us do action in asynchronous way – without page reloading. It is very useful and has affect on better user experience. We can for example add, hide or delete some content from site and there’s no need to reload whole page.

In WordPress ajax calls works a little bit differently than normally. Normally, if we want to load file with code, that would be called in ajax method, we must pass url to that file:

my-script.js:

$.ajax({
  url     :   '../my-ajax-code.php',
  method  :   'post',
  dataType:   'json',
  data    :   {mydata: data},
  success :   function(response) {
            //some action here
})

But in WordPress we pass url to early prepared object with data, that we want to pass through ajax. First, we must add script file, and then localize it, to let WordPress know, what data we want to use. We use wp_localize_script() to do it:

wp_localize_script( script-name, object_name, data-in-array(key =>value) )

All data added in wp_localize_script() are proccessing in admin-ajax.php file, so we set it as ajax url.

my-file.php

function lovecoding_enqueue_scripts() {
   wp_enqueue_script( 'lovecoding_script', plugins_url( 'public/js/lovecoding_script.js', __FILE__ ), array( 'jquery' ), true );
   wp_localize_script( 'lovecoding_script', 'lovecoding_script_ajax_object',
       array( 
           'ajax_url' => admin_url( 'admin-ajax.php' ),
       )
   );
}
add_action( 'wp_enqueue_scripts', 'lovecoding_enqueue_scripts' );

my-script.js:

$.ajax({
  url     :   lovecoding_script_ajax_object.ajax_url,   // wp_localize_script -> $object_name.$key_with_url
  method  :   'post',
  dataType:   'json',
  data    :   {action: 'my_function_ajax'},    // action: function, that is invoked by ajax 
  success :   function(response) {
            //do something with response
})

Now we must just write function which do what we want to do and add it do wp_ajax_$action or wp_ajax_nopriv_$action hook:

my-file.php

function lovecoding_my_function_ajax {
   // some code here, e.g. 
   // checking user permissions -> current_user_can()
   // verify nonce -> wp_verify_nonce()
   echo json_encode("your returned data - you must echo it, not return!");
   die();
}
add_action( 'wp_ajax_my_function_ajax', 'lovecoding_my_function_ajax' );        // to logged in users
add_action( 'wp_ajax_nopriv_my_function_ajax', 'lovecoding_my_function_ajax' );    // to not logged in users or users without permissions

Joanna

Leave a Reply

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