Accessing the target element in an AJAX request

Is my question too complex?

function showSkills(event,str) {

    xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            event.target.parentElement.parentElement.parentElement.nextElementSibling.innerHTML = this.responseText;
        }
    };
    xmlhttp.open("POST","skills.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("q=" + str);
    event.target.parentElement.parentElement.parentElement.nextElementSibling.style.display = "block";
}

The block is displayed, therefore the final line of code is fine. However, I am unable to post $q. I understand where the issue lies, but I'm unsure how to resolve it: If I use

document.getElementById("skills").innerHTML = this.responseText;
instead of
event.target.parentElement.parentElement.parentElement.nextElementSibling.innerHTML = this.responseText;
, everything works for <div id="skills'>, but not for skills2. I need to utilize this script separately for multiple div IDs (skills, skills2, skills3).

Here's My HTML:

<div class="bgimg" style="background-image:url('pic/a3.jpeg');">
  <h3 onclick="displayGrow(event)">bla bla</h3>
  <div id="sport" class="hide resetInput"><?php include 'sport.php'; ?></div>
  <div id="skills" class="hide resetInput"><?php include 'skills.php'; ?></div>
</div><!-- end of the 1st Parallax -->

<div class="bgimg" style="background-image: url('pic/a5.jpg');">
<h3 onclick="displayGrow(event)">bla bla</h3>
<div id="sport2" class="hide resetInput"><?php include 'sport.php'; ?></div>
<div id="skills2" class="hide resetInput"><?php include 'skills.php'; ?></div>
</div><!-- end of the 2nd Parallax -->

Plus, sport.php code:

<?php
include 'cookies.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  if (isset($_POST['q'])) {
  $q = $_POST['q'];
}}
?>

<div class="dropdown marginTop">
<button><!-- select sport -->
<?php // "select your sport"
    if (isset($q)) {
    $result = mysqli_query($con, 'SELECT ' .$language. ' FROM sports WHERE name1="' .$q. '" LIMIT 1');
    } else {
    $result = mysqli_query($con, 'SELECT ' .$language. ' FROM page WHERE title="selSport1" LIMIT 1');
    }
    $row = mysqli_fetch_row($result);
    print_r($row[0]);
?>
</button>
<div class="dropdown-content">
<?php // list of sports
     $sportlist = mysqli_query($con, 'SELECT * FROM sports WHERE title = "sports" ORDER BY ' .$language. ' ASC');
     while ($row = mysqli_fetch_array($sportlist)) {
         echo '
            <button class = "buttonList" value="' . $row[1] . '"';?>
            onclick="showSport(event, this.value); showSkills(event, this.value);" 
            <?php echo ' style="border:0;">' . $row[$language] . '</button>
        ';
     }
?>
</div>
</div>

Upon invoking showSport(), the button with value $q gets displayed in sport.php. This works well for both div IDs: sport and sport2. The showSkills() function should open skill.php in either <div id="skills"> or <div id="skills2"> and insert $q there. The section opens, but without $q. Any suggestions would be greatly appreciated.

Answer №1

event.target.parentElement.parentElement.parentElement.nextElementSibling
seems like quite a bit of DOM traversal for my liking. If I understand correctly, you are using the same function as an event handler for multiple elements. Have you considered passing the ID of the specific associated div as a parameter instead? Below is an example that demonstrates this method.

// Note, 'str' is just placeholder here
document.getElementById('event-div-1').addEventListener('click', showSkills.bind(null, 'skills1', 'foo'));
document.getElementById('event-div-2').addEventListener('click', showSkills.bind(null, 'skills2', 'foo'));
document.getElementById('event-div-3').addEventListener('click', showSkills.bind(null, 'skills3', 'foo'));


function showSkills(skills, event, str) {
  // Ajax stuff can go here
  document.getElementById(skills).style.display = 'block';
}
.skills {
  display: none;
}
<div class="skills" 
      id="skills1">1</div>
<div class="skills" 
      id="skills2">2</div>
<div class="skills" 
      id="skills3">3</div>

<div id="event-div-1">Click me for skills 1</div>
<div id="event-div-2">Click me for skills 2</div>
<div id="event-div-3">Click me for skills 3</div>

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

Streamlining async/await in for loops using Promise.all: A guide

I'm trying to understand how Promise.all() works in this code. I've learned that you can execute async operations concurrently with Promise.all() for better performance. Currently, the code uses nested for-loops (which is not ideal): type ListGro ...

Arranging buttons that are generated dynamically in a vertical alignment

Currently, I am in the process of creating a webpage for various items, and everything is going well so far. However, I have encountered an issue while attempting to vertically align the buttons that I am generating using JavaScript within the document. I ...

What is causing elements like divs, paragraphs, or text not to display within an ion-item after an ion-input is added?

I am currently working on validating a simple form and everything seems to be functioning properly. However, I have encountered an issue with displaying text messages within an ionic 3 list item. The ion-item consists of an ion-input element. When I place ...

Inquiring Minds: Exploring AJAX

I'm diving headfirst into this new concept and excited to learn. However, there are a few things that I'm unclear on: What are the implications if JavaScript is disabled in the browser? When utilizing MySQL databases for tasks like form validat ...

How can I use the JQuery .load() method to send a POST request after a successful ajax post?

Following a successful Ajax post, I am looking to render the template associated with POST using JQuery's .load() method in the handler function. Every time a successful POST is made, the GET request keeps getting called, resulting in the rendering of ...

Troubleshooting: Potential Reasons Why Registering Slash Commands with Options is Not Functioning Properly in Discord.js

While working on a Discord bot, I encountered an issue while trying to register a slash command with options for the ban command. The error message I received was: throw new DiscordAPIError(data, res.status, request); ^ DiscordAPIError: ...

Failure to receive Ajax XML data in success callback

I am struggling to access the book.xml file that is located in the same folder as other files. Everything seems fine, but the ajax function refuses to enter the success state and instead shows an [object object] error message. The XML file is very simple, ...

Firebase functions are giving me a headache with this error message: "TypeError: elements.get is not

Encountering the following error log while executing a firebase function to fetch documents and values from the recentPosts array field. Error: Unknown error status: Error: Unknown error status: TypeError: elements.get is not a function at new HttpsEr ...

Could implementing a click/keydown listener on each cell in a large React datagrid with thousands of cells impact performance?

Years ago, before the advent of React, I mastered linking events to tables by attaching the listener to the <tbody> and extracting the true source of the event from the event target. This method allowed for a single listener for the entire table, as ...

issue with HTML forms not triggering correct function when submitted

UPDATE: I have encountered an issue with my HTML page containing two forms, each with a single submit button. I attempted to call a specific function when the submit button is pressed. To achieve this, I included two <script> tags to handle the butto ...

Guide to automatically send a message when a new channel is added to a designated category using discord.js

Looking to develop a JavaScript Discord bot that automatically sends a message to new channels created under a designated category. The goal is to have the same message sent to every newly created channel. Seeking assistance from anyone knowledgeable on h ...

Ensuring that the redirect URL functions properly with AJAX

Can you guide me on how to implement an ajax request in my views that redirects the user to another page after a successful email submission? For instance, when a user submits their email successfully, I want to redirect them to another page. How can I ach ...

Displaying a JavaScript array containing multiple arrays

I have a collection of arrays, each containing a set of list items, which I am displaying using console.log(jobsList);. The output looks like this: The variable jobsList is generated by adding arrays created inside a for loop like this: for (var i=0; i ...

Creating double the mesh in THREE.js by utilizing identical vectors as their position coordinates

Recently, I upgraded from r67 to r69 in ThreeJS and now facing issues with referencing the positions of objects to a single vector. Prior to the update, this code snippet worked fine: var vector = new THREE.Vector3(50, 50, 50); _Mesh1.position = vector; ...

Is it possible to dynamically adjust the number of children in an array?

As a beginner in React, I've been exploring ways to manage an array of components from a parent component. My task involves creating a site where I can dynamically add or remove names to a list. However, I'm facing a challenge in figuring out the ...

Establish a spacing between a pair of geometries in THREE.JS

I need assistance with adjusting the distance between cylinders and sprites generated by this code. What steps can I take to achieve this? const THREE = this.context.three; const textureLoader = new THREE.TextureLoader(); const geometr ...

Using setState in a callback occasionally modifies the state within React Context

Check out the CodeSandbox demo: https://codesandbox.io/s/competent-dream-8lcrt In my implementation, I have created a modal using React context that provides access to 1) the modal's open state 2) the modal's configuration 3) methods for opening ...

Button click triggers CSS animation

Check out the interactive demo $(document).ready(function(){ $('#btn-animate').click(function(){ animate(); }); $('#btn-remove').click(function(){ $('.to-animate').removeClass('animate'); }); func ...

Styling the background of the endAdornment in a material-ui textfield using React

I tried following the instructions from this source: Unfortunately, the example code provided doesn't seem to be functioning properly now. Is there a way to achieve the same result without having that right margin so that it aligns better with the r ...

What steps do I need to take to implement React Form Builder 2 within my React JS project?

I'm struggling to figure out how to use react form builder 2 for my project. As a newcomer to React JS, I have typically just imported libraries after installing them, but in this case, I can't seem to find the tags to import. Can someone please ...