Fetch the information, insert following, and trigger a slide toggle

I am new to jQuery and I want to create a sliding table. The original table has 3 levels:

<ul class="categories">
<li id="category1">1 element</li>  //parentid=0
<li id="category2">2 element</li>  //parentid=0
<ul>
<li id="category3">1 element of element id2</li>  //parentid=2
<ul>
<li id="category4">1 element id3</li>  //parentid=3
</ul>
</li>
</ul>
</li>
</ul>

The first level elements have parentid = 0, with IDs incrementing from 1. Subsequent levels have nested parentids and their own unique ids.

Initially, the page loads with only the first level visible, where parentid = 0.

<ul class="categories">
<li id="category1">1 element</li>  //parentid=0
<li id="category2">2 element</li>  //parentid=0
</ul>

My goal is to click on a list item, retrieve its ID, use it to query a MySQL database in PHP, get the results back as a new table, and then slideToggle that new table under the respective list item.

PHP script handling the request:

if(isset($_POST['subcategory'])){
    $subcategory = str_replace('category', '', $_POST['subcategory']);  
    echo build_category_tree($subcategory); // Builds the UL tree
}

After receiving the data from the PHP function, I need to show and toggle the new list under the clicked list item.

Although the new UL is now connected, jQuery seems to be having trouble working with it. I have updated the script as shown below, but the issue persists.

Updated jQuery Function:

$(".tablecategoryname").on('click', function(){
    var $a = $(this).closest('li').attr('id');
    var $c = $(this).closest('li');

    $.ajax({
       type: "POST",
       url: "functions.php",
       data: {subcategory:$a},
       cache: false,
       success: function(data)
       {
            $(data).hide().insertAfter($c).slideDown(400);
       }
     });    
});

Answer №1

It's important that ID's are not just numbers or start with a number. Consider using something like #a1. Also, in the data parameter, sending an object is preferred over using equal signs.

$(".table li").on('click', function(){
    var self = this;
    $.ajax({
       type: "POST",
       url: "functions.php",
       data: {id : self.id},
       cache: false
    }).done(function(data) {
        // You should be returning valid HTML
        $(data).hide().insertAfter(self).slideDown(400);
    });
});

EDIT:

In your build_category_tree() function, make sure to return the HTML so you can echo it back to the ajax request:

if(isset($_POST['subcategory'])){
    echo $subcategory = str_replace('category', '', $_POST['subcategory']); 
    $ULtree = build_category_tree($subcategory); // builds the UL tree
    echo $ULtree; //echo back to Ajax
}

Answer №2

To make it work properly, ensure that you assign an id to the main ul element in order to locate its parent and toggle the list inside.

$("ul.umenu > li).click(function (e) {

    e.preventDefault();

    var element = $(this);

    if (element.parent().find("ul").is(":visible")) {
    } else {

        $("ul.umain> li > ul").slideUp();

        element.parent().find("ul").slideToggle("fast");

    }

});

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 measures can be taken to avoid the wrapping of cell table data in this particular scenario?

In this captured image : The HTML code below displays a table with various elements including an image, input fields, and dropdown menus. <div align="center"> <table cellpadding='1' cellspacing='1' width='98%' class ...

What is the method to ensure an element is displayed in Selenium WebDriver?

Looking for assistance on how to choose options from a dropdown when the element is not visible and has a boolean attribute? Here's the HTML code snippet: <select id="visualizationId" style="width: 120px; display: none;" name="visualization"> & ...

Utilizing distinct useState for mapped elements

I am struggling to find a solution on how to pass specific useState states to respective mapped elements. export const Polska = () => { const [riverVisible, setRiverVisible] = useState(false) const [mountainVisible, setMountainVisible] = useState(fa ...

Implementing Jquery to Identify the Matching Indices of Two Arrays

I need to find the indices of similar values in array1 and array2, and then save them in a variable named stored_index. array1 = ["50","51","52","53","54","55","56","57","58","59"]; array2 = ["59","55","51"]; The desired result for stored_index is: sto ...

Trouble with reading from a newly generated file in a node.js program

Whenever I launch my results.html page, I generate a new JSON file and use express.static to allow access to the public folder files in the browser. Although my application is functioning properly, I find myself having to click the button multiple times f ...

Issue with Vue JS function not providing the desired array output

I declared a property in my data model like this: someArray: [] A function returns an array: getMyArray: function (someId) { var result = [7, 8, 9, 10]; return result; } I'm assigning the result of the function to m ...

serving files using express.static

I have set up express.static to serve multiple static files: app.use("/assets", express.static(process.cwd() + "/build/assets")); Most of the time, it works as expected. However, in certain cases (especially when downloading many files at once), some fil ...

Struggling with dynamically updating fields based on user input in real time

I have a goal to update a field based on the inputs of two other fields. Currently, all the fields are manual input. Below is the code I'm using to try and make the "passThru" field update in real-time as data is entered into the other fields. The ma ...

How to use jQuery to autoplay audio without user interaction

In the process of creating a dashboard that provides sound notifications for new orders to users, I encountered an issue where the audio playback would fail due to lack of user interaction with the document. Despite trying solutions found in various posts, ...

The functionality of .bind() is malfunctioning on both Microsoft Edge and Google Chrome browsers

Everything seems to be running smoothly on Mozilla (version 103.0), but unfortunately, it's not performing as expected on Chrome or Microsoft Edge. $('#loading').bind('ajaxStart', function () { $(this).show(); }).bind('ajaxS ...

Utilizing getUserMedia to capture portrait shots with the back camera

I am encountering an issue with starting the back camera in portrait mode using navigator.mediaDevices.getUserMedia in React. The camera does not appear to be taking into account the constraints I have set. Below is how the code looks for initialization: ...

Is it possible to identify when an element has scrolled out of view just one time?

In an attempt to determine if an element has been scrolled out of view, I have implemented the following code: $(window).bind('scroll', function(){ var $btn = $('#intro div.summary a[href=#top]'); if($(window).scrollTop() > ...

Are there any plugins available for creating a progress bar using jQuery?

Looking for a Progress Bar jQuery Plugin Is there a jQuery plugin available that can dynamically adjust the length of a progress bar depending on a number input? Ideally, as the number decreases, the progress bar should also become shorter and vice versa. ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

Tips for triggering jquery code when a variable containing a CSS attribute is modified

I have a specific requirement where I need to reset the scrollleft value to 0 on my wrapper whenever a particular CSS property changes. Although I am new to using jQuery and haven't worked with variables much, I believe I need to create a variable to ...

What is the best method for updating the state of a dynamically created Switch component using React's setState()?

I have a dynamic creation of Switches based on a map like shown in the image: https://i.stack.imgur.com/jDLbS.png For example, using this code: const [enabled, setEnabled] = useState(false) return( ... {people.map((person) => ( ... ...

What is the comparable feature in Imagick PHP for optimizing Gifs?

Could someone help me understand how to reduce the size of a GIF using Imagick PHP? I am specifically trying to resample its color map to make it smaller and apply more compression. I have come across several tutorials suggesting the use of "-fuzz" with I ...

Encountering a "Cannot GET /PATH" error while developing a NUXT application due to a DOT present in

In my nuxt application, I encountered a peculiar issue. When I execute npm run dev, everything functions properly. However, after running npm run build and then npm run start, I face the error message stating cannot GET [path of the page here] I noticed t ...

Error encountered with Vuetify stepper simple component wrapper and v-on="$listeners" attribute

I'm working on developing a custom wrapper for the Vuetify Stepper component with the intention of applying some personalized CSS styles to it. My aim is to transmit all the $attrs, $listeners, and $slots. I do not wish to alter any functionality or ...

The ID attribute of Laravel blade file input is missing

Within my blade file, I have the following line of code: {!! Form::file('motivation', old('motivation'), ['id' => 'inputGroupMotivation', 'class' => 'custom-file-input']) !!} Although I ha ...