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