Getting dynamic data into JavaScript using Ajax

, ,

So there are often times you would like to have settings in the WordPress dashboard but use the data in a js file. I found that this can easily be done using a call to a WordPress Ajax url.

/* Javascript file */
var site_url = '';
jQuery( document ).ready(function() {
    var data = {
        'action' : 'dynamic_data' //this is the action of the wp_ajax call in this example
    } "/wp-admin/admin-ajax.php", data, function( response ) {
        site_url = response;


// can be placed in the child theme's functions.php file.

function dynamic_data_js_return() {
    //in this example I am returning the site_url
    echo site_url();
    die(); //important to have this otherwise your data could get additional characters added to the end of it.
add_action('wp_ajax_dynamic_data', 'dynamic_data_js_return');
add_action('wp_ajax_nopriv_dynamic_data', 'dynamic_data_js_return'); 


Posted on

February 26, 2021

Submit a Comment

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