WordPress.org

Forums

[resolved] ajaxurl is not defined (4 posts)

  1. DrLightman
    Member
    Posted 4 years ago #

    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.

  2. GBWorld
    Member
    Posted 4 years ago #

    How did you solve this problem? Because our Plugin is getting this error on the frontend too. thanks.

  3. coombesy
    Member
    Posted 4 years ago #

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

  4. 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
    }

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags