Skip to content
Related Articles

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Easy
  • Last Updated : 24 May, 2021
Improve Article
Save Article

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 Code -->
<!DOCTYPE html>
<html lang="en">
    <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=
    <!-- Button -->
    <button id="btn" value="hello world">
        Click On me!

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


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

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


    // Checking, if post value is
    // set by user or not
        // Getting the value of button
        // in $btnValue variable
        $btnValue = $_POST['btnValue'];
         // Sending Response
        echo "Success";


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!