Make WordPress Core

Opened 6 years ago

Closed 6 years ago

Last modified 6 years ago

#20424 closed defect (bug) (invalid)

wp_localize_script escapes url string.

Reported by: DennisSmolek Owned by:
Milestone: Priority: normal
Severity: normal Version: 3.3.1
Component: General Keywords:
Focuses: Cc:


When working down this tutorial http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/
(mentioned in WP CODEX)

it lists:

// embed the javascript file that makes the AJAX request
wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/ajax.js', array( 'jquery' ) );
// declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );

and the expected result is:

<script type="text/javascript" src="http://example.com/wordpress/wp-content/plugins/myajax/js/ajax.js"></script>
<script type="text/javascript">
/* <![CDATA[ */
var MyAjax = {
    ajaxurl: "http://example.com/wordpress/wp-admin/admin-ajax.php"
/* ]]> */

But on even a fresh install I'm getting:

var MyAjax = {"ajaxurl":"http:\/\/culturefarm.co\/et\/wp-admin\/admin-ajax.php"};
/* ]]> */
<script type='text/javascript' src='http://culturefarm.co/et/wp-content/plugins/ds-et/js/ajax.js?ver=3.3.1'></script>

It seems others are getting this too:

Now the stackoverflow guy says his works either way. Mine doesn't. If I manually write the code in the header I get it working but with such a common tutorial I figured it should be working right.

I know it now uses json_encode() which I'm guessing is doing the slashing. I can't seem to figure out why it's doing it though so I've done a fresh install with the same results so its either WP or my server.

Change History (3)

#1 @DennisSmolek
6 years ago

I discovered what the issue is.
The example given doesn't mention firing the code on any specific hook so it fires just on load plugins, which causes the slashes. If I move the code to wp_head it acts as expected. I realized the fix when I stopped ignoring the new debug notices.

#2 @scribu
6 years ago

  • Milestone Awaiting Review deleted
  • Resolution set to invalid
  • Status changed from new to closed

The slashes do not affect the actual value of the JS variable. There is no bug here.

#3 @scribu
6 years ago

To test, just do console.log(MyAjax.ajaxurl); in Firebug or the Chrome console.

Note: See TracTickets for help on using tickets.