WordPress PHP script not correctly being called by Javascript

I’ve redacted some info that’s not relevant.

I have a WordPress site and I’ve made a plugin meant for updating a database I’ve created. To put it simply I have a tool and I want to limit the amount of times a user can use that tool. So to do this I created a database with a user id and usage count column. I have another script which checks this database and if the usage column is a certain amount it won’t let the user use the tool and that works fine.

The issue I am facing is when I open the link to the plugin in the browser that’s https://REDACTED.com/wp-content/plugins/track_user_usage/track_user_usage.php it gets the user id and updates the database successfully with no problem but when I try and make it request the php script from a simple javascript/html script I created for a test it says success but doesn’t update the database.

Here is my PHP plugin with some stuff redacted:

<?php
/*
Plugin Name: Track User Usage
Plugin URL: REDACTED
Description: 
Version: 1.0
Author: REDACTED
*/

define('DB_SERVER2', 'REDACTED');
define('DB_USERNAME2', 'REDACTED');
define('DB_PASSWORD2', 'REDACTED');
define('DB_NAME2', 'REDACTED');

// Establish a persistent database connection
$conn = new mysqli(DB_SERVER2, DB_USERNAME2, DB_PASSWORD2, DB_NAME2);
$conn->autocommit(TRUE);
$conn->real_query("SET NAMES 'utf8'");

// Checking connection
if ($conn->connect_error) {
    die('Database connection failed: ' . $conn->connect_error);
}

function process_request() {

    global $conn;

    if ( ! defined( 'ABSPATH' ) ) {
        define( 'ABSPATH', '/home/REDACTED/REDACTED.com/' );
    }

     if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
     
        return;
    }

    include_once ABSPATH . '/wp-load.php';
    $userid = get_current_user_id();

    if ($userid == 0) {
        return;
    }

    $user_id = $userid; 
    $created_at = date('Y-m-d H:i:s'); 

    // Check if the user already exists in the table
    $sql_check_user = "SELECT * FROM tool_usage WHERE user_id = ?";
    $stmt_check_user = $conn->prepare($sql_check_user);
    $stmt_check_user->bind_param("i", $user_id);
    $stmt_check_user->execute();
    $result = $stmt_check_user->get_result();

    if ($result->num_rows > 0) {
        // User exists, update the usage count
        $sql_update_usage = "UPDATE tool_usage SET usage_count = usage_count + 1 WHERE user_id = ?";
        $stmt_update_usage = $conn->prepare($sql_update_usage);
        $stmt_update_usage->bind_param("i", $user_id);
        if ($stmt_update_usage->execute()) {
            
        } else {
            
        }
    } else {
        // User doesn't exist, insert a new record
        $usage_count = 1; // Initial usage count
        $sql_insert = "INSERT INTO tool_usage (user_id, usage_count, created_at) VALUES (?, ?, ?)";
        $stmt_insert = $conn->prepare($sql_insert);
        $stmt_insert->bind_param("iis", $user_id, $usage_count, $created_at);
        if ($stmt_insert->execute()) {
            
        } else {
            
        }
    }

    $stmt_check_user->close();
}

process_request();

$conn->close();
?>

If you are wondering why there are some else statements with nothing there it’s because there was echo statements but those were causing some issues for some reason so I just deleted them because I don’t really need them, but they were saying success.

And here is my simple test HTML/Javascript code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Track User Usage</title>
    <script>
        function trackUserUsage() {
            fetch('https://www.REDACTED.com/wp-content/plugins/track_user_usage/track_user_usage.php')
                .then(data => {
                    if (data.success) {
                        console.log('PHP script called successfully:', data);
                    } else {
                        console.error('PHP script error:', data);
                    }
                })
                .catch(error => {
                    console.error('Error calling PHP script:', error);
                });
        }
    </script>
</head>
<body>
    <button onclick="trackUserUsage()">Track User Usage</button>
</body>
</html>

I’ve tried a bunch of different ways for the Javascript and PHP for the past few hours with no success.

New contributor

user25236328 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật