Fetching dynamic information via AJAX for a jQuery tooltip

I have successfully loaded content via AJAX, including a UL element with li items that each have tooltips. Now I want to load tooltip content via AJAX for each individual li item. How can I achieve this?

Currently, I am making an AJAX call to load the li items using the following code:

    //start AJAX request
    $.get(
        bs_url + '/ajax/' + ajax_action + '/', // server-side script
        ajax_params, // data for server-side script
        function(data, textStatus) {
            $("li", list_elm).remove();
            $("div#related_questions_container").hide("slow");
            if (data) {
                $("div#related_questions_container").show("slow");
                list_elm.append(data);

                // add the tooltip to AJAX loaded content
                $("ul#related_questions li a").tooltip();
            }
        },
        'html'
    );

Now, how can I make an AJAX call to load data specifically for each tooltip? Each <a> element within the li items has an id attribute value that I want to pass as a parameter to the AJAX function responsible for loading the tooltip content.

Below is the HTML snippet that is loaded via AJAX to populate the ul element with li items:

<?php
    foreach($this->related_queries_data as $o){
?>
<li><a href="#" title="<?php echo htmlspecialchars($o['oQuery']->getTitle()) ?>" id="id_<?php echo htmlspecialchars($o['oQuery']->getId()) ?>" ><?php echo htmlspecialchars($o['oQuery']->getTitle()); ?></a></li>
<?php
    }
?>

Answer №1

My solution involved utilizing the 'this' keyword, which points to the current element being hovered over, specifically an <a> tag. By leveraging this, I could access the unique ID stored in the 'id' attribute of each <a> element. Subsequently, I utilized jQuery to perform a GET request and fetch the content for the tooltip related to that particular ID.

Below is how my final JavaScript code was structured:

    // Initiating AJAX request
    $.get(
        bs_url + '/ajax/' + ajax_action + '/', // Server-side script
        ajax_params, // Data for server-side script
        function(data, textStatus) {
            // alert("Response Data Loaded");

            $("li", list_elm).remove();
            $("div#related_questions_container").hide("slow");

            if (data) {
                $("div#related_questions_container").show("slow");
                list_elm.append(data);

                // Adding tooltips to dynamically loaded content
                $("ul#related_questions li a").tooltip({
                    content: function(callback){
                        var query_id = this.id.substring('id_'.length)
                        var tooltip_content_ajax_action = 'get-query-info';
                        var tooltip_content_ajax_params = { 'query_id' : query_id}

                        // Getting HTML partial for given query_id
                        $.get(
                            bs_url + '/ajax/' + tooltip_content_ajax_action + '/', // Server-side script
                            tooltip_content_ajax_params,
                            function(data, textStatus) {
                                if (data) {
                                    callback(data);
                                }
                            },
                            'html'
                        )

                    }
                });
            }
        },
        'html'
    );

Update: While the initial approach worked, it posed efficiency issues as triggering a tooltip would trigger a new AJAX request for its content, resulting in a noticeable delay (2-3 seconds) before loading. To address this, I modified the implementation so that tooltip content was loaded during the initial AJAX call fetching the <li> elements. The content is encapsulated within a hidden div by default, which is then referenced in the tooltip plugin's callback for efficient loading.

    // Initiating AJAX request
    $.get(
        bs_url + '/ajax/' + ajax_action + '/', // Server-side script
        ajax_params, // Data for server-side script
        function(data, textStatus) {
            // alert("Response Data Loaded");

            $("li", list_elm).remove();
            $("div#related_questions_container").hide("slow");

            if (data) {
                $("div#related_questions_container").show("slow");
                list_elm.append(data);

                // Adding tooltips to dynamically loaded content
                $("ul#related_questions li a").tooltip({
                    content: function(callback){
                        var tooltip_content_div = $("div#query_" + this.id);
                        callback(tooltip_content_div.html());

                    }
                });
            }
            
        },
        'html'
    );

The following snippet represents the HTML fetched through the AJAX request:

<?php
    foreach($this->related_queries_data as $o){
?>
<li>
    <a href="#" title="<?php echo htmlspecialchars($o['oQuery']->getTitle()) ?>" id="id_<?php echo htmlspecialchars($o['oQuery']->getId()) ?>" ><?php echo htmlspecialchars($o['oQuery']->getTitle()); ?></a>
    <div id="query_id_<?php echo htmlspecialchars($o['oQuery']->getId()) ?>" class="query_tooltip_content"><!-- set to display:none by default -->
        <div id="query_info">
            <div style="width:50%; float:left;">
                <ul>
                    <li><b>Raised by: </b><?php echo htmlspecialchars($o['oQuery']->getRaisedUser()->getName())?></li>
                    <li><b>Raised on: </b><?php echo htmlspecialchars($o['oQuery']->getRaised()->format('d-m-Y H:i:s'))?></li>
                </ul>
            </div>

            <div style="width:50%; float:left;">
                <ul>
                    <li><b>Assigned to: </b><?php $oUser = $o['oQuery']->getAssignedUser(); echo htmlspecialchars(is_null($oUser)?'-':$oUser->getName());?></li>
                    <li><b>Status: </b><span class="<?php echo $o['oQuery']->getPriority()->getName() ?>"><?php echo htmlspecialchars($o['oQuery']->getStatus()->getDisplayName())?> <?php echo (!is_null($o['oQuery']->getDateQueryClosed()) ? ' on '.$o['oQuery']->getDateQueryClosed()->format('d-m-Y') : '') ?></span></li>
                </ul>
            </div>

            <div style="clear:both;"></div>
        </div></div></li>
<?php
    }
?>

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

"Combining Array Elements in jQuery: A Guide to Merging Two Array Objects

enter : var b= [{ "cat_id": "1", "cat_name": "teaching" }]; var a= [ { "username": "r", "password": "r" }]; I desire the following result: [{"username":"r","password":"r","cat_id":"1","cat_name":"teaching"}] ...

What is the best way to utilize jQuery for selecting all child elements excluding a specified filter element?

I have a main div and I want to select all elements within the main div, excluding the start div and its children (as shown in the code with pink blocks). The .filter() method displays all children elements of the start div. Using .not() will show the st ...

"The issue arises when attempting to use Ajax to call a PHP script

Here is the jQuery script I am working with: <script> $(document).ready(function(){ $("#username").blur(function() { //remove all the class add the messagebox classes and start fading $("#msgbox").removeClass().addClass('messagebox&ap ...

Executing a function in ExpressJS at regular intervals of 24 hours

Can someone share the most effective method to schedule an automated task every 24 hours in ExpressJS? I have thoroughly researched possible solutions but haven't found any option other than using an infinite loop. Is there only one way to achieve th ...

Encountered a parsing error when attempting to integrate SCSS with webpack and babel setup

I am facing an issue while trying to integrate SCSS into my webpack and babel setup. When running npm run build, I encounter an error that I'm unfamiliar with. As a beginner in using webpack and babel, I'm unsure about the necessary changes requ ...

"Issues Arising from Compatibility between Internet Explorer, jQuery,

I need help creating a function that will transfer items from the basket to the cart. The code I have written works well in Firefox and Chrome, however, it is not recognizing the products. var modals_pool = {}; $('.deal_order_btn').on('clic ...

How can we effectively streamline these if statements for better organization and efficiency?

Currently, I am dealing with a straightforward if condition structure and aiming to keep the code as DRY (Don't Repeat Yourself) as possible. I believe that I have achieved optimal dryness for my specific situation by utilizing object keys as pointers ...

Review the file's content prior to uploading

Before uploading a zip or rar file to the server, I need to ensure that the content is safe and not malicious. Let me paint the picture for you. In my web project, there are two types of users: 1: Regular registered users 2: Project administrators Any ...

Update the canvas box's color when you interact with it by clicking inside

I'm in the process of developing a reservation system and I'm looking to implement a feature where the color of a Canvas changes when clicked. The goal is for the color to change back to its original state when clicked again. Snippet from my res ...

bespoke design picture holder

Is it possible to create a custom-shaped image container without using <div />? I encounter an issue when trying to add corners on top of the #content-box as shown in this screenshot: . The corner images only cover half of the block element, with th ...

Clear the input field value when the onClick event occurs, and retain the value if not changed

When I initially set a default value in the input field, it is important that this value is removed when clicked inside the field. However, if the inserted value is left blank and the mouse cursor moves away from the field, the default value must be restor ...

What is the best way to achieve complete code coverage for ajax requests, including success and failure callbacks, using Jasmine and Blanket.js?

Here is a sample code snippet for adding a row: var Utils = {}; Utils.genericAddRowPost = function(url) { return $.post(url); }; Utils.genericAddRow = function(dataSource, url) { genericAddRowPost(url).done(function(data, textStatus, jqXHR) { ...

formula for an arbitrary velocity vector

In the game I'm developing, I want the ball to move in a random direction on the HTML canvas when it starts, but always with the same velocity. The current code I have is: vx = Math.floor(Math.random() * 20) vy = Math.floor(Math.random() * 20) Howev ...

Perform an action when the timer reaches zero

I am working with a database entry that contains the following information: { _id:"fdjshbjds564564sfsdf", shipmentCreationTime:"12:17 AM" shipmentExpiryTime:"12:32 AM" } My goal is to create a timer in the front end ...

Is it necessary to manually set the "if-no-match" parameter in an AJAX request when the server includes an Etag in the

My query may seem straightforward, but I have yet to come across a satisfactory answer during my research. I am currently utilizing a Jquery ajax request to fetch data from a server that hosts a rest API. The server is configured to set the Etag and Cach ...

An error was returned by Ajax when attempting to make the ajax call

I have a custom ajax function that successfully updates my database. After the update, I call the successAlert() function. Now, I want to incorporate an error handling mechanism by calling the error function in case of any errors. However, during testing, ...

Making an Ajax call without using the push.js library

I'm currently utilizing Ratchet 2 for my application development. I am attempting to implement a basic ajax request and retrieve the response as shown below: function attemptLogin() { var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpReques ...

Conceal mobile button

Welcome to my website: Is there a way to hide the button on mobile phones? I want to create different buttons specifically for mobile devices. Below is the HTML code for the buttons. HTML <a href="http://site9171756.91.webydo.com/Info.html" target="p ...

The jQuery change event is not triggered for <input type="file"> when a file is dropped on the label

I am currently developing a drag and drop file uploader that can be activated by either clicking the label or dragging a file onto the label. The input field includes a jQuery on change event that is triggered when a file is selected. However, it only see ...

Utilizing JQuery to Extract Data from a Nested JSON Array

My API is returning a JSON string with various values that I need to extract using JQuery. "[ ["West Baton Rouge test hello world", "1"], ["LSU Parking \u0026 Transportation Services", "2"], ["demokljafsk", "3"], ["latest", "19"], ...