How to send button value to PHP backend via POST using ajax ?
To send button value to PHP backend via POST using ajax, you can follow the below steps:
- Create a button in HTML with a unique id and value attribute:
<button id="myButton" value="buttonValue">Click me</button>
- Add an event listener to the button using JavaScript/jQuery:
$(document).ready(function(){
$('#myButton').click(function(){
var buttonValue = $(this).val();
$.ajax({
type: 'POST',
url: 'backend.php',
data: {buttonValue: buttonValue},
success: function(response){
console.log(response);
}
});
});
});
- In the backend PHP file, retrieve the button value using the $_POST superglobal:
if(isset($_POST['buttonValue'])){
$buttonValue = $_POST['buttonValue'];
// do something with the button value
}
Alternatively, you can also use the FormData object to send the button value via POST using ajax. Here's an example:
- Create a button in HTML with a unique id and value attribute:
<button id="myButton" value="buttonValue">Click me</button>
- Add an event listener to the button using JavaScript/jQuery:
$(document).ready(function(){
$('#myButton').click(function(){
var buttonValue = $(this).val();
var formData = new FormData();
formData.append('buttonValue', buttonValue);
$.ajax({
type: 'POST',
url: 'backend.php',
data: formData,
processData: false,
contentType: false,
success: function(response){
console.log(response);
}
});
});
});
- In the backend PHP file, retrieve the button value using the $_POST superglobal:
if(isset($_POST['buttonValue'])){
$buttonValue = $_POST['buttonValue'];
// do something with the button value
}
Note: Make sure to include the jQuery library in your HTML file if you're using jQuery.