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

$ajax_nonce = wp_create_nonce("iwhq_beginner_select_course");

<script type="text/javascript" language="javascript">

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
        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){ 
    }); //close jQuery.ajax(
    return false;


And this is the function in functions.php

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


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


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 */
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.

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() );

Need Your Help

applying class to parent if child has it using jQuery

javascript jquery

How can I use jQuery when I have this HTML code I need to add the class name to the parent li only when the child has the class name high.

Get Custom File Version Info from a Native binary using C#

c# c++ version

I've got a bunch of native (C++) binaries that I want to scan and retrieve version information about from a C# console application. Using System.Diagnostics.FileVersionInfo I am able to get the ac...