The purpose of this article is to pass multiple JSON objects as data using the jQuery $ajax() method in an HTML document.
Approach: Create a button in an HTML document to send JSON objects to a PHP server. In the JavaScript file, add a click event listener to the button. On clicking of the button, a request is made to PHP file using jQuery $ajax() method by which multiple JSON objects are passed to the server.
HTML Code: The following code demonstrates the design or structure of the user interface. On click of the HTML button, it gives the response by the PHP server in the resultID HTML div.
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 >
< center >
< h2 style = "color:green" >GeeksforGeeks</ h2 >
< div class = "container" >
< b >Pass multiple JSON objects</ b >
< br />< br />
< button type = "button" id = "btn" >
Click on me!
</ button >
< div style = "height:10px" ></ div >
< div id = "resultID" ></ div >
</ div >
</ center >
</ 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 ;
}
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” used in the above HTML code. It handles the click() event for the button by using jQuery ajax() method and passing the data to a PHP server file i.e action.php
script.js
$(document).ready(() => {
$( "#btn" ).click(() => {
let obj1 = { "name" : "John Doe" };
let obj2 = { "name" : "Duke" };
$.ajax({
url: 'action.php' ,
type: 'POST' ,
data: {
obj1,
obj2
},
success: (response) => {
$( "#resultID" ).show().html(response);
}
})
});
});
|
Note: You can pass as many JSON objects by using comma(,) separated values i.e. obj1, obj2, obj3,..
PHP code: The following is the code for the file “action.php” used in the above JavaScript code.
PHP
<?php
if (isset( $_POST [ 'obj1' ]) && $_POST [ 'obj2' ])
{
$obj1 = $_POST [ 'obj1' ];
$obj2 = $_POST [ 'obj2' ];
echo "Success" ;
}
?>
|
Output :

multiple data passing and getting response