WordPress.org

Support

Support » How-To and Troubleshooting » [Resolved] ajaxurl is not defined

[Resolved] ajaxurl is not defined

  • 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.

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

    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 ‘[Resolved] ajaxurl is not defined’ is closed to new replies.
Skip to toolbar