WordPress.org

Make WordPress Core

Opened 2 years ago

Closed 2 years ago

Last modified 2 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:

Description

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"
};
/* ]]> */
</script>

But on even a fresh install I'm getting:

var MyAjax = {"ajaxurl":"http:\/\/culturefarm.co\/et\/wp-admin\/admin-ajax.php"};
/* ]]> */
</script>
<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:
http://wordpress.stackexchange.com/questions/41989/wp-localize-script-escaping-my-url-fix-or-alternative
http://wordpress.org/support/topic/wp_localize_script-adds-a-backslash-admin-ajaxphp

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)

comment:1 DennisSmolek2 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.

comment:2 scribu2 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.

comment:3 scribu2 years ago

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

Note: See TracTickets for help on using tickets.