UPDATE: Message to all future readers
We have found the solution! Make sure to check out my answer along with charlietfl's answers below.
Question Before Solution
I've created a script that sends values to a page called x.php. Each red container has its own inputs and button, so when you click on any
of those red container buttons, it will send their container input values to page x.php for echoing.
The issue I'm facing is that it can only send the request from the first red container button. If I try doing the same for other containers, it only sends the first red container input values for echoing
and not their respective values. How can I modify it so that it sends the correct red container values?
This is how it should look once it works correctly
Below is the code snippet
index.php
<style>
.dataContainer{
background-color: red;
width: 185px;
position: relative;
margin-bottom: 25px;
}
.dataContainerDesign .a,.b,.send{
display: block;
margin: auto;
}
</style>
<script>
document.addEventListener('DOMContentLoaded', function(){
var containerButtons = document.querySelectorAll('.dataContainer .send');
for (var i = 0; i < containerButtons.length; i++) {
containerButtons[i].addEventListener('click', perContainer);
}
var xhr= new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState === 4){
document.querySelector('.dataContainer').innerHTML= xhr.responseText;
}
};
function perContainer(){
var data = new FormData();
//Variable structure
var a= document.querySelector('.a').value;
var b= document.querySelector('.b').value;
//
//Data variables
data.append('a', a);
data.append('b', b);
//
xhr.open('POST','x');
xhr.send(data);
}
});
</script>
<div class='dataContainer dataContainerDesign'>
<input class='a' type='text'>
<input class='b' type='text'>
<button class='send'>Send</button>
</div><!--</dataContainer>-->
<div class='dataContainer dataContainerDesign'>
<input class='a' type='text'>
<input class='b' type='text'>
<button class='send'>Send</button>
</div><!--</dataContainer>-->
<div class='dataContainer dataContainerDesign'>
<input class='a' type='text'>
<input class='b' type='text'>
<button class='send'>Send</button>
</div><!--</dataContainer>-->
<div class='dataContainer dataContainerDesign'>
<input class='a' type='text'>
<input class='b' type='text'>
<button class='send'>Send</button>
</div><!--</dataContainer>-->
x.php
<p style='display: inline-block;'>
<?php
$a= $_POST['a'];
$b= $_POST['b'];
echo 'Sent Values: ';
echo $a.','.$b;
?>
</p>