Reputation: 437
For the record I searched through every other time this was asked but could not find the solution
I'm simply trying to add ajax content to a page for logged out users and failing dispite using wp_ajax_nopriv. I've tried deactivating all plugins and that didn't help. Although I do want to lock down access to the backend admin solely to the admin, I do not currently have that implemented.
Loading the script
function html5blank_header_scripts()
{
if ($GLOBALS['pagenow'] != 'wp-login.php' && !is_admin()) {
wp_register_script('globalJs', get_template_directory_uri() . '/js/global.js', array('jquery'), '1.0.0'); // Custom scripts
wp_enqueue_script('globalJs'); // Enqueue it!
wp_localize_script(
'globalJs',
'ajax_object',
array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 )
);
}
}
PHP ajax function
add_action( 'wp_ajax_new_ajax_event_template', 'new_ajax_event_template' );
add_action( 'wp_ajax_nopriv_new_ajax_event_template', 'new_ajax_event_template' );
function new_ajax_event_template() {
global $post;
$postID = $_POST["post_id"];
$post = get_post($postID);
<------- lots of stuff that works for logged in user ----->
die();
}
JQuery ajax script
$(document).on("click", ".title[data-ajax='post']", function() {
$post_id = $(this).data("id");
$post_type = $(this).data("type");
$post_url = $(this).data("url");
var historyData = $(".wrapper").attr("data-history");
if (!historyData){
historyData = [];
}
else{
historyData = JSON.parse(historyData);
}
historyData.push({
id: $post_id,
type: $post_type,
url: $post_url
});
var data = {
action : 'new_ajax_'+ $post_type +'_template',
post_id : $post_id
};
$("#main").empty().hide();
$.ajax({
url : ajax_object.ajax_url,
type : 'post',
data : data,
success: function(html) {
$("#main").append(html);
history.pushState('data', '', $post_url);
$(".wrapper").attr("data-id", $post_id);
$(".wrapper").attr("data-history", JSON.stringify(historyData));
$("#main").fadeIn("fast");
}
});
});
This is all works perfectly for logged in users but fails for logged in users and I have no idea why. There's nothing in the functions.php that should prevent this.
Upvotes: 2
Views: 3144
Reputation: 437
I fixed this by making sure admin-ajax.php was setup in the head
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
Upvotes: 0
Reputation: 1108
Check below scenario, I could not say surely
1) Did you get jQuery error?, check in browser console and if have anything clear it.
2) Check admin-ajax.php response in browser developer tool -> network (PFA)
Upvotes: 1