Skip to content
Related Articles

Related Articles

How to send button value to PHP backend via POST using ajax ?
  • Difficulty Level : Easy
  • Last Updated : 30 Nov, 2020

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

filter_none

edit
close

play_arrow

link
brightness_4
code

<!-- 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>

chevron_right


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



Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Button DOM
let btn = document.getElementById("btn");
  
// Adding event listner 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);
    });
});

chevron_right


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

PHP

filter_none

edit
close

play_arrow

link
brightness_4
code

<?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";
    }
?>

chevron_right


Output:

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :