How to send dynamic key value pair to PHP with jQuery ?
The purpose of this article is to send dynamic key-value pairs to the PHP back-end using jQuery AJAX in an HTML document.
Create two input fields i.e one for a key and the second one for value, and a button (to send key-value pair) in an HTML document. Assign a unique id to both the fields and to the button. In the JavaScript file, add an event listener to the button i.e click. On clicking of the button, a request is made to PHP file using jQuery Ajax.
HTML Code: The following code is for structure.
index.html
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< meta name = "viewport"
content = "width=device-width, initial-scale=1.0" >
< link rel = "stylesheet" href = "style.css" >
< script src =
</ script >
< script src = "script.js" ></ script >
</ head >
< body >
< div class = "container" >
< h1 >Dynamic Key Value Pair</ h1 >
< input type = "text" name = "key" id = "key"
placeholder = "Enter Key" >
< br >
< input type = "text" name = "value" id = "value"
placeholder = "Enter Value" >
< br >
< button type = "button" id = "btn" >
Send Data
</ button >
</ div >
</ body >
</ html >
|
CSS Code: The following code is the content for the file “style.css” used in the above HTML code.
style.css
.container {
border : 1px solid rgb ( 73 , 72 , 72 );
border-radius: 10px ;
margin : auto ;
padding : 10px ;
text-align : center ;
}
h 1 {
margin-top : 10px ;
}
input[type= "text" ] {
padding : 10px ;
border-radius: 5px ;
margin : 10px ;
font-family : "Times New Roman" , Times, serif ;
font-size : larger ;
}
button {
border-radius: 5px ;
padding : 10px ;
color : #fff ;
background-color : #167deb ;
border-color : #0062cc ;
font-weight : bolder ;
cursor : pointer ;
}
button:hover {
text-decoration : none ;
background-color : #0069d9 ;
border-color : #0062cc ;
}
|
JavaScript Code: The following code is the content for the file “script.js” file used in the above HTML code.
main.js
$(document).ready(() => {
$( "#btn" ).click(() => {
const key = $( "#key" ).val();
const value = $( "#value" ).val();
let data = {};
data[key] = value;
$.post(
"action.php" ,
{
data,
},
(response) => {
alert(`Response from sever side is: ${response}`);
}
);
});
});
|
PHP code: The following is the code for the file “action.php” used in the above HTML code.
action.php
<?php
if (isset( $_POST [ 'data' ])) {
$data = $_POST [ 'data' ];
echo "Success" ;
}
?>
|
Output:
dynamic key value pair
Last Updated :
14 Jul, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...