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.

Do not forget to add WordPress nonce

functions.php

function lovecoding_enqueue_scripts() {
   wp_enqueue_script( 'lovecoding_script', get_theme_file_uri() . '/assets/js/script.js', array( 'jquery' ), true );
   wp_localize_script( 'lovecoding_script', 'lovecoding_script_ajax_object',
       array( 
           'ajax_url'   => admin_url( 'admin-ajax.php' ),
           'ajax_nonce' => wp_create_nonce( 'lovecoding_ajax_nonce' )
       )
   );
}
add_action( 'wp_enqueue_scripts', 'lovecoding_enqueue_scripts' );

script.js:

$.ajax({
  url     :   lovecoding_script_ajax_object.ajax_url,   // from functions.php file: wp_localize_script -> $object_name.$key_with_url
  method  :   'post',
  dataType:   'json',
  data    :   {action: 'my_function_ajax', _ajax_nonce: lovecoding_script_ajax_object.ajax_nonce, some_data: my_data },    // 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:

functions.php

function lovecoding_my_function_ajax {
   // check nonce
   check_ajax_referer( 'lovecoding_ajax_nonce', '_ajax_nonce' );
   // get data sent by ajax and do something with them
   $my_data = sanitize_text_field( $_POST['some_data'] );
   // return data to jQuery ajax
   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

When we send data from PHP to jQuery ajax using echo json_encode(data), we must use die() function at the end of code, to avoid generate extra output, which may break our data.

Joanna

2 Replies to “How to use ajax in WordPress – on frontend and admin side”

  1. Hej, dzięki za ten post.
    Jak połączyć AJAX z “wp_nav_menu”? Chciałbym, żeby po kliknięciu na zakładkę np “o firmie”, ta załadowała się bez odświeżenia (powiedzmy z jakąś animacją). Chciałbym tez, aby każda strona korzystała ze swojego szablonu:

    Przekopałem całą sieć i nie mogę się niczego chwycić… Możesz coś podpowiedzieć?
    Dziękuję!

Leave a Reply

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