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);
});
});
Try replacing the
with
the 0 error is a default error in wordpress for ajax most of the time it is die; will break everything. hope this helps
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):
js
Are you quite sure that
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():