Wednesday, November 20, 2024
Google search engine
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 Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments