Make WordPress Core

Opened 12 years ago

Closed 12 years ago

Last modified 12 years ago

#20424 closed defect (bug) (invalid)

wp_localize_script escapes url string.

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


When working down this tutorial
(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=""></script>
<script type="text/javascript">
/* <![CDATA[ */
var MyAjax = {
    ajaxurl: ""
/* ]]> */

But on even a fresh install I'm getting:

var MyAjax = {"ajaxurl":"http:\/\/\/et\/wp-admin\/admin-ajax.php"};
/* ]]> */
<script type='text/javascript' src=''></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
12 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
12 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
12 years ago

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

Note: See TracTickets for help on using tickets.