WordPress Ajax returns full html page from functions.php, not echo

I am using a wordpress ajax call to return simple content from a function in wordpress theme functions.php. However, a full html page is returned instead.

Here is the ajax call

Read More
<?php   
$ajax_nonce = wp_create_nonce("iwhq_beginner_select_course");
?>

<script type="text/javascript" language="javascript">
jQuery(document).ready(function(){

jQuery("#beg_golf_course").change(function() {  //do this when course changes

//in WordPress ajaxurl always points to admin-ajax.php
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
var course_id = 4; 

//Do the ajax
    jQuery.ajax({
        type: "POST", 
        url: ajaxurl,

        //NOTE - the action parameter calls the function in functions.php
        data: { action: 'select_course_aj', course_id: course_id, _ajax_nonce: '<?php echo $ajax_nonce; ?>' },


        //display alert on success
        success: function(html){ 
            alert(html);
        } 
    }); //close jQuery.ajax(
    return false;

    });
});
</script>

And this is the function in functions.php

function select_course_func(){
echo $_POST["course_id"];
die();
}

add_action('wp_ajax_select_course_aj','select_course_func');

The HTML of the page containing the jquery ajax call is actually displayed in the alert instead of the echo.

Any geniuses out there able to tell me why?

Thanks
Mark

Related posts

Leave a Reply

2 comments

  1. OK, Problem solved. See my last 3 comments above plus…

    !defined(‘DOING_AJAX’) is a constant that can be used to test that the user is not performing an ajax request. I combined this with my logic for redirecting non-admins to the frontend and it works now.

    /* check the role of current loged in user for redirection */
    add_action('admin_init','rt_checkRole');
    function rt_checkRole() {
    
        global $wp_roles;
        $currentrole ='';
        foreach ( $wp_roles->role_names as $role => $name ) {
            if ( current_user_can( $role ) ){
                        $currentrole = $role;
                    }
            }
            if(!defined('DOING_AJAX') && (!$currentrole || ($currentrole != 'administrator' && $currentrole != 'editor'))){
                wp_redirect (site_url().'/front-end-login/');
            }
    }
    

    Found out about !defined(‘DOING_AJAX’) at https://wordpress.stackexchange.com/questions/26100/redirect-out-of-wp-admin-without-losing-admin-ajax-php

    Thanks to all who commented.

  2. If you want to do ajax call for non admin user you should use the code below, that will disallow wp-admin access for non admin user but allow ajax call for every user, logged in or logged out user

    function my_admin_init(){
        if( !defined('DOING_AJAX') && !current_user_can('administrator') ){
            wp_redirect( home_url() );
            exit();
        }
    }
    add_action('admin_init','my_admin_init');