How to safely pass post_id and user_id via AJAX to the backend (prevent user from changing it via JS)?

I’m having code (user rates post) where I’m passing user_id and post_id via AJAX to the back-end. My concern is that user can change values in JS and pass another’s user id or post id. How do I prevent that?

Here is a simplified code (without nonces for the sake of example):

$(‘input[name=”rate1″]:radio’).change(function () {
var rating = $(“input[name=’rate1′]:checked”).val();

$.ajax({
url : ‘<?php echo admin_url(‘admin-ajax.php’) ?>’,
type : ‘post’,
data : {
‘action’: ‘rate_the_post’,
‘post_id’: <?php echo $post_id; ?>,
‘user_id’: <?php echo $user_id; ?>,
‘rating’ : rating
}
}).done(function (data) {
console.log(data);
});
});

In the backend I get variables and update the post based on them:

function rate_post() {
global $wpdb;

$post_id = intval($_POST[‘post_id’]);
$user_id = intval($_POST[‘user_id’]);
$rating = intval($_POST[‘rating’]);

…update DB with $wpdb;
}

So how do I make sure I have a valid user_id of current user and post_id of current post in the backend?

Read more here:: How to safely pass post_id and user_id via AJAX to the backend (prevent user from changing it via JS)?

Leave a Reply

Your email address will not be published. Required fields are marked *