Is the regular ajax request method safe or I should use admin-ajax.php?

On the homepage I have some links:

<a class=”link” data-id=”1″>first link</a>
<a class=”link” data-id=”2″>second link</a>
<a class=”link” data-id=”3″>third link</a>

When one of these links is clicked, I want to send an ajax request to a php file to update the Database to increase views column of that post.

$(document).ready(function(){
$(document).on(‘click’, ‘.link’, function(e){

var post_id = $(this).data(‘id’);

$.ajax({
url: “views.php”,
type: ‘POST’,
data: {id: post_id},
success: function(){
alert(“done”);
}}); // ajax

}); // on click

}); // ready

In views.php:

//Check if the id is posted.
if( isset($_POST[‘id’]) ){

//Assigning the id to a variable.
$id = $_POST[‘id’];

//Check if the id is an integer.
$pattern = ‘/[0-9]/’;
if( preg_match($pattern, $id) ){

//Check that the user didn’t visit that post before.
$post_cookie = ‘p_’ . $id;
if( !isset($_COOKIE[$post_cookie]) ){

//Insert or update if the post id exists.
$query = $conn->prepare(‘INSERT INTO posts (id, views) VALUES (:id, 1) ON DUPLICATE KEY UPDATE views = views+1’);
$query->bindValue(‘:id’, $id, PDO::PARAM_INT);
$query->execute();

//Set a cookie with the post id to indicate that the post is viewed.
setcookie( $post_cookie, ‘1’);

}// No cookie with that name (the user didn’t visit that post).
} // id matches the pattern.
} // id is posted.

I could you other options that the posts id to add/update the views, But I’m wondering if that way is safe or I should use admin-ajax.php.

The posts are custom posts from Database, Not WordPress posts

Read more here:: Is the regular ajax request method safe or I should use admin-ajax.php?

Leave a Reply

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