Support » Fixing WordPress » ajaxurl is not defined

  • Resolved DrLightman

    (@drlightman)


    Hi, I was reading HERE that since WP 2.8 a global variable “ajaxurl” is defined to be used in ajax calls.

    The fact is, before starting writing the code I tested the value of it but it says it’s not defined. My app already uses JQuery.

    add_action('wp_head', 'myheadfunc');
    function myheadfunc()
    {
    	?>
    <script type="text/javascript" language="javascript">
    //<![CDATA[
    jQuery(document).ready(function () {
    	alert( ajaxurl );
    });
    //]]>
    </script>
    	<?php
    }

    In the console I get:

    ajaxurl is not defined
    alert( ajaxurl );

    Please help.

    edit: Ok reading more carefully the link, it says that on the frontend that variable is not automatically defined.

Viewing 3 replies - 1 through 3 (of 3 total)
  • How did you solve this problem? Because our Plugin is getting this error on the frontend too. thanks.

    coombesy

    (@coombesy)

    unfortunately that javascript variable is not supported anymore. You have to grab the location using php and print it to the front.

    Moderator Samuel Wood (Otto)

    (@otto42)

    WordPress.org Admin

    The ajaxurl is only defined in the admin section. If you need the url on the front end, use <?php echo admin_url('admin-ajax.php'); ?> instead.

    If you need it for use by a separate static JS file on the front end, add this to the plugin/theme/wherever:

    <?php
    add_action('wp_head','pluginname_ajaxurl');
    function pluginname_ajaxurl() {
    ?>
    <script type="text/javascript">
    var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
    </script>
    <?php
    }
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘ajaxurl is not defined’ is closed to new replies.