I want to make an AJAX request on every select value change to update the real value from database. I’m coding inside a shortcode on functions.php
. I have a select
element like this one below,
echo '<select name="changeValue" onchange="changeValue(' . $user->ID . ', this.options[this.selectedIndex])">'
At the end of the shortcode, I do:
?>
<script type="text/javascript">
function changeValue(id, valueElement) {
jQuery.post(
"<?php echo admin_url('admin-ajax.php'); ?>",
{
'action': 'update_value',
'data': {
user_id: id,
value: valueElement.value
}
},
function(response){
console.log(response)
}
);
}
</script>
<?
}
add_shortcode('the_shortcode', 'the_shortcode');
function update_value() {
$user_id = $_POST['data']['user_id'];
$value= $_POST['data']['value'];
echo $user_id . ' - ' . $empresa;
//return update_user_meta($user_id , 'value', $value);
wp_die();
}
add_action( 'wp_ajax_update_value', 'update_value' );
add_action( 'wp_ajax_nopriv_update_value', 'update_value' );
My code works when I’m logged as Admin. However if I’m logged as another user, console.log(response)
returns the whole HTML page content. What am I doing wrong?
EDIT: Another difference is that when logged as Admin, admin-ajax.php
returns 200 OK
, whereas when logged as a user it returns 302 Found
.