Skip to content
PHP Logo

Is it possible to execute PHP scripts through buttons without input fields?

Yes, it is possible to execute PHP scripts through buttons without input fields by using JavaScript to trigger a PHP script when a button is clicked. This can be achieved by making an AJAX request to the PHP script when the button is clicked.

php
<?php
if(isset($_POST['button_click'])) {
    // Your PHP script logic here
    echo "Button clicked!";
    exit;
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Execute PHP Script on Button Click</title>
</head>
<body>
    <button id="myButton">Click Me</button>

    <script>
        document.getElementById("myButton").addEventListener("click", function() {
            var xhr = new XMLHttpRequest();
            xhr.open("POST", "", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            xhr.send("button_click=true");

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText);
                }
            };
        });
    </script>
</body>
</html>