I’m pretty new to AJAX so I’m struggling a little with my functionality for my WordPress site.
I have a dropdown list of countries and when a user selects a different country, I would like to update the cookie (which is already set) and therefore the page should load the new cookie without reloading the page.
At the moment I have to hit refresh for this to show the correct country code from using the code below, whereas I’d have hoped AJAX would do this without refreshing the page:
<?php echo "Value is: " . $_COOKIE['country']; ?>
My code is below, but I’m sure some of it may not be needed or is wrong.
JS
$('.single-country-select').on("change", function (e) {
var country_code_value = $('.single-country-select').val();
var sendData = {
action: 'country_change_ajax_function',
country_code_value: country_code_value
};
$.ajax({
url: ajaxadminurl.ajaxurl,
type: 'POST',
data: sendData,
dataType: 'html',
cache: false,
success: function(data) {
// SET COOKIE HERE??
}
});
});
functions.php
function country_change_ajax_function() {
$country_code_value = $_POST['country_code_value'];
setcookie('country', $country_code_value, time() + (86400 * 30), '/');
exit;
}
add_action('wp_ajax_country_change_ajax_function', 'country_change_ajax_function');
add_action('wp_ajax_nopriv_country_change_ajax_function', 'country_change_ajax_function');
I’ve also got some code at the top of my header that sets the cookie automatically:
if(!isset($_COOKIE['country'])) {
$get_user_country_code = simplexml_load_file("http://www.geoplugin.net/xml.gp?ip=".getRealIpAddr());
if ($get_user_country_code === false) {
$user_country_code = 'GB';
setcookie('country', 'GB', time() + (86400 * 30), '/');
} else {
$user_country_code = $get_user_country_code->geoplugin_countryCode;
setcookie('country', $user_country_code, time() + (86400 * 30), '/');
}
}
Any help would be much appreciated. Thanks!