Reputation: 55
I create plugin for Wordpress and use AJAX in plugin but AJAX response 0. I try to solve this problem by following this answer but can't solve my problem.
This is my handler function
if( is_admin()) {
add_action( 'admin_menu', 'language_redirect_add_config_page' );
}
else {
add_action( 'plugins_loaded', 'preference_language' );
add_action( 'wp_enqueue_scripts', 'enqueue' );
add_action( 'wp_ajax_preference_language', 'preference_language' );
add_action( 'wp_ajax_nopriv_preference_language', 'preference_language' );
}
function language_redirect_config_page() {
add_options_page( __( 'Language Redirect Setting' ), __( 'Language Redirect' ), 'manage_options', basename( __FILE__ ), '' );
}
function enqueue() {
wp_enqueue_script( 'ajax-script', plugins_url( '/js/plugin-script.js', __FILE__ ), array('jquery') );
wp_localize_script( 'ajax-script', 'ajax_object', array(
'ajax_url' => admin_url( 'admin-ajax.php' )
)
);
}
// Handler function...
function preference_language() {
$language = $_POST['language'];
if($language == 'th') {
header( 'Location: ' . site_url('th') );
}
else {
return;
}
die;
}
And this my AJAX script
jQuery(document).ready(function($) {
var language = localStorage.getItem('language');
var data = {
action: 'preference_language',
language: language
};
$.post(
ajax_object.ajax_url,
data,
function(response) {
console.log(response);
});
});
Upvotes: 1
Views: 313
Reputation: 121
Are you quite sure that
localStorage.getItem('language')
actually holds a value that is or could be 'th'?
To be sure that your code works you could use the following code instead of your current preference_language():
function preference_language() {
$language = $_POST['language'];
if($language == 'th') {
echo "language is th.";
}
else {
echo "language is not th.";
}
die;
}
Upvotes: 0
Reputation: 5937
header( 'Location: ' . site_url('th') );
You can't set headers after output has been rendered. Remember ajax is called from the frontend and obviously output has already started.
heres an way of doing this (untested):
function preference_language() {
$language = $_POST['language'];
if($language == 'th') {
echo site_url('th');
} else {
return;
}
exit;
}
js
jQuery(document).ready(function($) {
var language = localStorage.getItem('language');
var data = {
action: 'preference_language',
language: language
};
$.post(
ajax_object.ajax_url,
data,
function(response) {
window.location = response;
});
});
Upvotes: 0
Reputation: 184
Try replacing the
die;
with
exit;
the 0 error is a default error in wordpress for ajax most of the time it is die; will break everything. hope this helps
Upvotes: 1