¿Cómo enviar el valor del botón al backend de PHP a través de POST usando ajax?

El propósito de este artículo es enviar el valor del botón al back-end de PHP usando AJAX en un documento HTML.

Enfoque: cree un botón en un documento HTML y asígnele una identificación. En el archivo JavaScript, agregue un detector de eventos al botón, es decir, haga clic. Luego, la solicitud se realiza al archivo PHP usando jQuery Ajax.

Código HTML:

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=
"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">
    </script>
</head>
 
<body>
 
    <!-- Button -->
    <button id="btn" value="hello world">
        Click On me!
    </button>
</body>
 
</html>

Código JavaScript: El siguiente es el código para el archivo “script.js”.

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);
    });
});

Código PHP: El siguiente es el código para el archivo “action.php”.

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

Producción:

Publicación traducida automáticamente

Artículo escrito por asmitsirohi y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *