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:
<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
wp_localize_script()
now usesjson_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: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 withoutadmin_
to include also in frontend.now you can use the data from json inside your script, example
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.