What causes the initial button to transmit their unique values, while the rest are unable to do so within the same container

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

See screenshot in GIF format

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>

Answer №1

The issue arises when using document.querySelector('.a'), as it will only return the first element with that class in the entire document.

To retrieve the class within the specific button's siblings, you need to target the parent of the button and query within that parent instead.

In this simplified demo, I have omitted XHR and FormData to focus on logging the associated values to the console instead.

document.addEventListener('DOMContentLoaded', function() {

  var containerButtons = document.querySelectorAll('.dataContainer .send');

  for (var i = 0; i < containerButtons.length; i++) {
    containerButtons[i].addEventListener('click', perContainer);
  }
  
});


function perContainer(evt) {
  // Get the clicked button from the event object
  let button = evt.currentTarget,
  // isolate the parent container
    div = button.parentNode;

  //query within the parent container
  var a=  div.querySelector('.a').value;
  var b=  div.querySelector('.b').value;  

  console.log([a, b]);
}
<div class='dataContainer dataContainerDesign'>
  <input class='a' type='text' value="a1">
  <input class='b' type='text' value="b1">
  <button class='send'>Send</button>
</div>
<!--</dataContainer>-->

<div class='dataContainer dataContainerDesign'>
  <input class='a' type='text' value="a2">
  <input class='b' type='text' value="b2">
  <button class='send'>Send</button>
</div>
<!--</dataContainer>-->

<div class='dataContainer dataContainerDesign'>
  <input class='a' type='text' value="a3">
  <input class='b' type='text' value="b3">
  <button class='send'>Send</button>
</div>
<!--</dataContainer>-->

<div class='dataContainer dataContainerDesign'>
  <input class='a' type='text' value="a4">
  <input class='b' type='text' value="b4">
  <button class='send'>Send</button>
</div>
<!--</dataContainer>-->

Answer №2

Shoutout to charlietfl for guiding me through the solution - thanks to their help, I was able to crack this problem and now I'm sharing charlietfl's answer as a hint for others. However, I've also included my own approach alongside charlietfl's method in case any future readers are curious about the end result.

Here is the fully functional code.

index.php

<style>

.dataContainer{
  background-color: red;
  width: 205px;
  position: relative;
  margin-bottom: 25px; 
}

.dataContainerDesign .first_name,.last_name,.send{
  display: block;
  margin: auto;
}

 </style>

    <script>

document.addEventListener('DOMContentLoaded', function(){

var dataContainerSendButtons = document.querySelectorAll('.dataContainer .send');

 for (var i = 0; i < dataContainerSendButtons.length; i++) {
   dataContainerSendButtons[i].addEventListener('click', dataContainerProcess);
 }

function dataContainerProcess(execution){

var send = execution.currentTarget;
  var dataContainer = send.parentNode;

var xhr= new XMLHttpRequest();
xhr.onreadystatechange = function(){

    if(xhr.readyState === 4){
        dataContainer.innerHTML= xhr.responseText;
    }
}

    var data = new FormData();

  //Variable structure
   var first_name=  dataContainer.querySelector('.first_name').value;
   var last_name=  dataContainer.querySelector('.last_name').value;
   var image=  dataContainer.querySelector('.image').files[0];
//

//Data variables
data.append('first_name', first_name);
data.append('last_name', last_name);
data.append('image',image);
//
    xhr.open('POST','x'); 
    xhr.send(data);
}

});

    </script>

    <div class='dataContainer dataContainerDesign'>
      <input class='first_name' type='text'>
      <input class='last_name' type='text'>
      <input class='image' type='file'>
      <button class='send'>Send</button>
    </div><!--</dataContainer>-->

    <div class='dataContainer dataContainerDesign'>
      <input class='first_name' type='text'>
      <input class='last_name' type='text'>
      <input class='image' type='file'>
      <button class='send'>Send</button>
    </div><!--</dataContainer>-->

    <div class='dataContainer dataContainerDesign'>
      <input class='first_name' type='text'>
      <input class='last_name' type='text'>
      <input class='image' type='file'>
      <button class='send'>Send</button>
    </div><!--</dataContainer>-->

    <div class='dataContainer dataContainerDesign'>
      <input class='first_name' type='text'>
      <input class='last_name' type='text'>
      <input class='image' type='file'>
      <button class='send'>Send</button>
    </div><!--</dataContainer>-->

x.php

<?php

$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];

if($_FILES['image']['name'] != '')
{
 $image_test = explode('.', $_FILES['image']['name']);
 $image_ext = end($image_test);
 $image_prefix= 'random';
 $image_file_name = $image_prefix . uniqid() . '.' . $image_ext;
 $image_directory = 'images/';
 $image_location = $image_directory.$image_file_name;  
 move_uploaded_file($_FILES['image']['tmp_name'], $image_location);

 $profile_image= $image_location;
}

?>

<style>

img{
    display: block;
    width: 200px;
    height: 200px;
    margin: auto;
}

h1{
    text-align: center;
    margin: 0;
}

</style>

<img src='<?php echo $profile_image; ?>'>
<h1><?php echo $first_name; ?></h1>
<h1><?php echo $last_name; ?></h1>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason behind the specific sequence in which this JavaScript console log is displayed?

Extracted from Chapter 11 of the book Eloquent Javascript, this code snippet showcases the use of Promises. You can interact with the code in a sandbox environment here. I recently dabbled with the Promises featured in this snippet and was surprised to fin ...

Error occurred during the parsing of an AJAX response

Hello, I am currently exploring the world of JavaScript and jQuery. I recently encountered a situation where I initiated an AJAX call in my code and received an unexpected response. https://i.sstatic.net/AUHb7.png My current challenge revolves around imp ...

The toLowerCase method seems to be malfunctioning along with several other functions

JS var score = 0 var yes = "yes" var pokemonName = []; var bg = []; var index = 0; document.getElementById('repete').style.visibility = 'hidden'; (function asyncLoop() { background = bg[num = Math.floor(Math.random() ...

The <span> tag with content-editable attribute loses selection when the mouse button is released

I'm attempting to utilize a content-editable span tag as an inline text input box with variable width. Everything is functioning properly, except for the issue of not being able to select the entire text when focusing on the box. When tabbing to the e ...

Persisting dynamically generated table information into a multidimensional array

I've created a dynamic table and now I'm trying to extract the data from it and store it in a multidimensional array. However, I keep encountering an exception/error that says "Cannot set property of 0 to undefined". https://i.sstatic.net/W8B9j.p ...

The function was triggered upon the form loading, instead of being activated when the button was clicked

The issue I am facing is that in the code snippet below, the function readCSV() is not being triggered when buttons for filepath1 and filepath2 are clicked. The function is only executed on form load. I was expecting it to work on button click as well. I ...

Creating HTML Divs with Equal Heights

I have written this JavaScript code, but I feel like there might be some redundancy. Does anyone have suggestions on how to improve and optimize this code? var boxHeights = []; $('.box').each(function() { boxHeights.push( $(this).outerHeight ...

Bringing in PeerJs to the NextJs framework

Currently delving into NextJs and working on creating an audio chat application, I've hit a roadblock while attempting to import PeerJs. An error message keeps popping up saying 'window is not defined'. import Peer from 'peerjs'; ...

What is the scope parameter for the facebook-node-sdk in node.js?

https://github.com/amachang/facebook-node-sdk I decided to utilize this module in order to create a Facebook-integrated login for my node.js project, following the example provided with express: var express = require('express'); var Facebook = ...

Is your React conditional rendering malfunctioning due to state issues?

I am attempting to create a component that will only be displayed after clicking on a search button. Below is the current code that I have: Update After making some changes, I am now encountering this error: Error: ERROR in /home/holborn/Documents/Work ...

Multiple layers of SVG text with consistent widths and dynamic heights

I have a challenge in mind where I want to implement a text effect that automatically adjusts its width while maintaining proportional heights. My goal is to stack multiple words on top of each other to create a visual style similar to the example image b ...

The error message that you are seeing is indicating that the `contracts` property of `this.state

Despite having encountered this issue before, I am still struggling to find a solution. The code snippet for fetching data is as follows: async componentDidMount(){ try { const res = await fetch('https://example.com/data.json'); ...

Create a parent dropdown class that contains two separate bootstrap dropdowns nested within it

I am encountering an issue with my dropdown menus. I have 2 dropdown menu items under the same parent dropdown class. However, when I click on dropdown action 1, it displays the body of dropdown menu 2 items instead. <!DOCTYPE html> <html> < ...

Issue with displaying YouTube videos in HTML causing them to be downloaded instead of playing

I'm currently facing an issue with loading a video on my HTML page using the following code: <video v-for="(data, key) in projectData.videos" :key="key" width="320" height="240" controls> <source :src="data.url"> </video> One ...

Incorrect comparison of floats within arrays resulted in inaccurate results

I am currently working on a project that involves comparing values in an Array which are dynamically fetched from a website, and I'm using Selenium-IDE to assist with this comparison. However, I've noticed that the values are being compared as s ...

The current situation is not effective; it is causing an error saying "Uncaught TypeError: Cannot read property 'substring' of undefined"

Encountering an error "Uncaught TypeError: Cannot read property 'substring' of undefined" while debugging in Chrome Inspector, with the following code: <script type="text/javascript"> $(function countComments() { var mcount = '/ ...

Having difficulty manually concealing the launch image on the physical device

When testing my trigger.io app on the Android simulator or my Nexus phone, I can manually hide the launch image through code successfully. However, when running the app on the iOS simulator, the launch image remains visible. Additionally, when debugging di ...

Vue automatically populates an empty array with an Observer object

I have been attempting to create an empty array in the data and then fetch a JSON from the server to populate it. The issue I am encountering is that the array consistently includes an extra Observer object, so when I log it, I see: empty items array: ...

use the useState hook to update an array of objects by adding a new object

Currently, I am in the process of developing a straightforward order list web application using react hooks. Within this app, there is an orders state that gets updated whenever a user clicks on a product image in the shopping panel. When this action occur ...

Is there a way to transform a date format like "22-07-2020 12:00" into ISO date format?

Can anyone help me convert a date from this format: 22-07-2020 12:00 to the following format: 2020-07-07T11:39:02.287Z I'm unsure how to achieve this, any advice would be appreciated. Thanks! ...