wp_localize_script escaping my url – fix or alternative

Here is my wp_enqueue_script and wp_localize_script – which i am using to run an Ajax call.

wp_enqueue_script( 'function', plugin_dir_url( __FILE__ ) . 'function.js', array( 'jquery', 'json2' ) );
wp_localize_script( 'function', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

While debugging this problem arose:

Read More
<script type='text/javascript'>
/* <![CDATA[ */
    var MyAjax = {"ajaxurl":"http://mydomain.com/wp-admin/admin-ajax.php"};
    /* ]]> */
    </script>

As you can see my url is been escaped out and i have no idea why… is there a possible fix or alternative method for what i am trying to do?

Thanks in advance

Related posts

Leave a Reply

2 comments

  1. wp_localize_script() now uses json_encode() which means a multidimensional array will now work for the passed data. And, HTML entity decoding only applies to the first level of the array.

    Better is an way to use json and default js possibilities from WP.

    At first, i add the options from the database via script and json_encode to wp header:

        add_action( 'admin_enqueue_scripts', 'fb_print_scripts' );
    
        function fb_print_scripts() {
            global $current_screen;
    
            if ( isset( $current_screen -> id ) && ! in_array( $current_screen -> id, array( 'post', 'page' ) ) )
                return;
    
            if ( is_plugin_active_for_network( plugin_basename( __FILE__ ) ) )
                $options = get_site_option( 'my_options_id' );
            else
                $options = get_option( 'my_options_id' );
    
            if ( ! $options )
                return;
            ?>
            <script type="text/javascript">
                var my_json_object = <?php echo htmlspecialchars( json_encode( $options ) ); ?>;
            </script>
            <?php
        }
    

    after this i read this data via javascript; the script include via wp_enqueue_script; the follow example init only in admin, you can change the hook without admin_ to include also in frontend.

    add_action( 'admin_enqueue_scripts', 'fb_admin_enqueue_scripts' );
    
    function fb_admin_enqueue_scripts( $where ) {
    
        if ( ! in_array( $where, array( 'post.php', 'post-new.php', ) )
            return;
    
        $suffix = defined('SCRIPT_DEBUG') && SCRIPT_DEBUG ? '.dev' : '';
    
        wp_enqueue_script(
            self :: get_textdomain() . '_script',
            plugins_url( '/js/my_script' . $suffix. '.js', __FILE__ ),
            array( 'jquery', 'my_other_script' ),
            '',
            TRUE
        );
    
    }
    

    now you can use the data from json inside your script, example

    jQuery( document ).ready( function( $ ) {
    
        if ( typeof my_json_object == 'undefined' )
            return;
    
    // debug in console of Browser
    console.dir( my_json_object ); 
    
    });
    
  2. The issue comes from when you are firing the wp_localize_script call. Most likely you are just writing that code into your plugin which loads far too early.

    I struggled with the problem for a while as well. If you wrap the code in a function and use add_action on wp_head it works as expected.

    function ajaxurl() {
    wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
    wp_localize_script( 'my-ajax-request', 'MyAjax', array(
    // URL to wp-admin/admin-ajax.php to process the request
    'ajaxurl'          => admin_url( 'admin-ajax.php' ),
    
    // generate a nonce with a unique ID "myajax-post-comment-nonce"
    // so that you can check it later when an AJAX request is sent
    'postCommentNonce' => wp_create_nonce( 'myajax-post-comment-nonce' ),
    )
    );
    
    
    }
    add_action('wp_head', 'ajaxurl');