How to send button value to PHP backend via POST using ajax ?
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
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport" content =
"width=device-width, initial-scale=1.0" >
< script src = "script.js" ></ script >
< script src =
</ script >
</ head >
< body >
< button id = "btn" value = "hello world" >
Click On me!
</ button >
</ body >
</ html >
|
JavaScript code: The following is the code for “script.js” file.
Javascript
let btn = document.getElementById( "btn" );
btn.addEventListener( "click" , () => {
let btnValue = btn.value;
$.post( 'action.php' , {
btnValue: btnValue
}, (response) => {
console.log(response);
});
});
|
PHP code: The following is the code for “action.php” file.
PHP
<?php
if (isset( $_POST [ 'btnValue' ]))
{
$btnValue = $_POST [ 'btnValue' ];
echo "Success" ;
}
?>
|
Output:
Last Updated :
12 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...