Saturday, September 6, 2025
HomeLanguagesHow to send button value to PHP backend via POST using ajax...

How to send button value to PHP backend via POST using ajax ?

The purpose of this article is to send the value of the button to PHP back-end using AJAX in an HTML document.

Approach: Create a button in HTML document and assign an Id to it. In JavaScript file add an event listener to button i.e click. Then the request is made to PHP file using jQuery Ajax.

HTML code:

HTML




<!-- HTML Code -->
<!DOCTYPE html>
<html lang="en">
  
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content=
        "width=device-width, initial-scale=1.0">
  
    <!-- JavaScript file -->
    <script src="script.js"></script>
  
    <!-- jQuery Ajax CDN -->
    <script src=
    </script>
</head>
  
<body>
  
    <!-- Button -->
    <button id="btn" value="hello world">
        Click On me!
    </button>
</body>
  
</html>


JavaScript code: The following is the code for “script.js” file.

Javascript




// Button DOM
let btn = document.getElementById("btn");
  
// Adding event listener to button
btn.addEventListener("click", () => {
  
    // Fetching Button value
    let btnValue = btn.value;
  
    // jQuery Ajax Post Request
    $.post('action.php', {
        btnValue: btnValue
    }, (response) => {
        // response from PHP back-end
        console.log(response);
    });
});


PHP code: The following is the code for “action.php” file.

PHP




<?php
  
    // Checking, if post value is
    // set by user or not
    if(isset($_POST['btnValue']))
    {
        // Getting the value of button
        // in $btnValue variable
        $btnValue = $_POST['btnValue'];
        
         // Sending Response
        echo "Success";
    }
?>


Output:

Dominic
Dominichttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Dominic
32271 POSTS0 COMMENTS
Milvus
82 POSTS0 COMMENTS
Nango Kala
6641 POSTS0 COMMENTS
Nicole Veronica
11806 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11869 POSTS0 COMMENTS
Shaida Kate Naidoo
6754 POSTS0 COMMENTS
Ted Musemwa
7030 POSTS0 COMMENTS
Thapelo Manthata
6705 POSTS0 COMMENTS
Umr Jansen
6721 POSTS0 COMMENTS