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"> <!-- CSS file --> <link rel="stylesheet" href="style.css"> <!-- jQuery Ajax CDN --> <script src= </script> <!-- JavaScript file --> <script src="script.js"></script> </head> <body> <div class="container"> <h1>Dynamic Key Value Pair</h1> <!-- Input Field for key --> <input type="text" name="key" id="key" placeholder="Enter Key"> <br> <!-- Input Field for value --> <input type="text" name="value" id="value" placeholder="Enter Value"> <br> <!-- Button to send key value pair --> <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; } h1 { 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(() => { // Adding 'click' event listener to button $("#btn").click(() => { // Fetching key's input field data const key = $("#key").val(); // Fetching values input field data const value = $("#value").val(); // Initializing array of objects to // store key-value pairs let data = {}; // assigning key-value pair to data object data[key] = value; // jQuery Ajax Post Request $.post( "action.php", { data, }, (response) => { // response from PHP back-end 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 // Checking, if post value is // set by user or not if (isset($_POST['data'])) { // getting key-value pair object // in $data variable $data = $_POST['data']; // Sending Response echo "Success"; } ?> |
Output:
dynamic key value pair
