I would like to do an ajax request in my theme.
If I am login to the Back Office, the request does, but if I'm not logged in, the returns is null... What's the solution please ?
In my view :
$.ajax({
type: "POST",
url: 'http://www.mysite.com/wp-admin/admin-ajax.php',
data: $('#EventForm').serialize()+'&action=event_form',
success: function(response){
if(response == 1){
alert('ok');
} else {
alert('no ok');
}
});
In the functions.php (works only if I am log in back Office)
add_action('wp_ajax_event_form', 'ajax_event_form');
function ajax_event_form(){
global $wpdb;
...
echo true;
die;
}
From the Codex: wp_ajax_nopriv_(action)
executes for users that are not logged in. So, if you want it to fire on the front-end for both visitors and logged-in users, you can do this:
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
Create a plugin and add this:
<?php
/*
* Plugin Name:ajax
*/
function my_ajax_callback_function() {
echo "hiii";
print_r($_POST);
exit();
}
add_action( 'wp_ajax_my_action_name', 'my_ajax_callback_function' );
// If called from admin panel
add_action( 'wp_ajax_nopriv_my_action_name', 'my_ajax_callback_function' );
Create a js and add this:
(function($) {
$(document).ready(function(e) {
$.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: 'POST',
data: {
action: "my_action_name","name":"hithin","age":"27"
},
success: function (data, textStatus, jqXHR) {
console.log(data);
}
});
}
})(jQuery);
The ajax request in WordPress works by classifying user in two categories
1) User with login privilege. 2) User without login privileges.
So if you are logged in(even as a subscriber) your ajax function will be triggered i.e.
add_action('wp_ajax_event_form', 'ajax_event_form');
this will call 'ajax_event_form' function.
To make this work for non-logged in users you will have to write this below your ajax action
add_action('wp_ajax_nopriv_event_form', 'ajax_event_form');
So your code will be like:
add_action('wp_ajax_event_form', 'ajax_event_form');
add_action('wp_ajax_nopriv_event_form', 'ajax_event_form');
function ajax_event_form(){
global $wpdb;
...
echo true;
die;
}