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


AJAX (Asynchronous JavaScript and XML) makes web pages more responsive, interactive, and dynamic by enabling server communication without requiring a page to load. JavaScript is used to send and receive data from a server using various technologies, including XML, JSON, and HTML. In these, JSON is the most popular.

AJAX is frequently used to transmit information from a web page to a server-side script, like a PHP script. The XMLHttpRequest object, included in most contemporary web browsers, can be used for this. You can establish a connection to a given URL, send data to that URL, and then wait for a response from the server using the XMLHttpRequest object. We can also use the JQuery ajax package for the ajax request to simplify it. JavaScript is used to make a POST request to a PHP script on the server when the button is pressed. The button's value is transmitted in the request as data, and the PHP script can access it by utilizing the superglobal variable $_POST. The PHP script can then process the data, replying to JavaScript with an update to the website.

AJAX's primary purpose is to enable dynamic content updates on web pages without requiring a complete page refresh, and this can enhance user experience and increase the responsiveness of websites.

Using Ajax Method

It is possible to divide the AJAX method's button value sent to a PHP backend into two parts.

The JavaScript code must be configured in the first stage to record the button's click event. An AJAX request to the PHP backend can be made once the click event is fired. Remembering that the AJAX call needs to be configured to utilise the POST method rather than the GET method by default is crucial.

The data from the button's value must be included in the second step's AJAX request. You can retrieve this information by accessing the button's value property, and the data can then be included in the AJAX call's data parameter.

The PHP backend needs to be configured to receive the data from the AJAX call after the AJAX call has been made. The $_POST array can be accessed to accomplish this. The name of the button's value property will serve as the array's key, and the button's value will serve as its value. After the processes mentioned above have been finished, the button value will now be transmitted to the PHP backend via POST, utilizing the AJAX method.

You can submit a POST request with the value of a button using jQuery's ajax() method, as seen below −

Syntax

// Button value
let buttonValue = $("#myButtonId").val();

// or, let buttonValue = document.getElementById("#myButtonId").value;

// Send the POST request
$.ajax({
   url: "php_file_name.php",
   type: "POST",
   data: { buttonValue: buttonValue },
   success: function(response) {
      
      // Do something if ajax request is successful
   }
});

Example

In the below example, we send a button value to the PHP backend server along with two field values, email and password. We are using the JQuery library to make ajax requests. First, we create an index.php file with our HTML and JavaScript code. JavaScript code consists of the code for making AJAX requests. It sends the form data as well as the button value. The formSubmit.php is the backend file of PHP which takes the AJAX POST data.

Index.php

<html>
<head>
   <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>
</head> 
<body>
   <h3>Send button value to <i>PHP backend</i> via POST using <i>AJAX</i></h3>
   <h4 id = "message" style = "color: #00ff00"></h4>
   <div id = "myForm" onsubmit = "submitFunc()">
   <div>
      <label for = "email">Email</label>
      <input type = "email" name = "email" id = "email">
   <div>
   <div>
      <label for = "password">Password</label>
      <input type = "password" name = "password" id = "password">
   <div>
      <button onclick = "submitFunc()" id = "submitButton" name = "myBtn" value = "XYZ">Submit</button>
   </div>
   <script>
      var name = document.getElementById('name');
      var pass = document.getElementById('password');
      var message = document.getElementById('message');
      var message = document.getElementById('myBtn');
      function submitFunc() {
         $.ajax({
            type: "POST",
            url: "formSubmit.php",
            data: {email: email.value, password: pass.value, btn: btn.value},
            success: function(result){
               message.innerHTML = 'Email and Password send successfully!'
            },
            error: function (err) {
               message.innerHTML = 'Email and Password send failed!'
            }
         });
      }
   </script>
</body>
</html> 

formSubmit.php

<?php
   if(isset($_POST)){
      $email = $_POST["email"];
      $password = $_POST["password"];
      $btn = $_POST["btn"];
      $result = "Email: $email, Password: $password, Button: $btn";
      echo $result;
   }
?>

This is the full demonstration of the button value sent to PHP. It is essential to set up your backend PHP file to accept and process the request; otherwise, it may give errors that also need to be handled.

Updated on: 10-Mar-2023

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements