Dynamically show data in the Tooltip using AJAX

A tooltip is a small pop-up element which shows information when moving the mouse pointer to the element.

You can dynamically update the tooltip content with AJAX if you don’t want to fix the content while creation.

You can add the tooltip to the element with Bootstrap, jQueryUI, or any other library.

I am using the jQuery UI library in the tutorial.

In the demonstration, I am displaying the list of users and dynamically load information on the tooltip with AJAX on mouse hover.

Dynamically show data in the Tooltip using AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. jQuery
  5. PHP
  6. CSS
  7. Demo
  8. Conclusion

1. Table structure

I am using users table in the tutorial example.

CREATE TABLE `users` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `username` varchar(80) NOT NULL,
  `name` varchar(80) NOT NULL,
  `gender` varchar(10) NOT NULL,
  `email` varchar(60) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

2. Configuration

Create a config.php for database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

3. HTML

Create <span> element with the user’s name in the <div class='content'> container. In the <span> specify title (use to enable tooltip from the library on the element) and id attribute.

You can define any default value in the title attribute.

Completed Code

<link href='jquery-ui.css' rel='stylesheet' type='text/css'> 
<script src='jquery-3.2.1.min.js' type='text/javascript'></script> 
<script src='jquery-ui.js' type='text/javascript'></script> 
<script src='script.js' type='text/javascript'></script>
  
<div class='container'>
 
 <div class='content'>
   <span title='Please wait..' id='user_1'>Yogesh Singh</span>
 </div>
 
 <div class='content'>
   <span title='Please wait..' id='user_2'>Sonarika Bhadoria</span>
 </div>

 <div class='content'>
   <span title='Please wait..' id='user_3'>Vishal Sahu</span>
 </div>

 <div class='content'>
   <span title='Please wait..' id='user_4'>Sunil</span>
 </div>
</div>

4. jQuery

Initialize tooltip on the <span> element by calling tooltip() method on the selector.

In the tooltip() method define two options track and open.

  • track – Enable to change the position of tooltip according to the mouse movement when it set to true.
  • open – Get the user id by splitting element id. Send the AJAX request and pass the userid as data. On successful callback update the content option with the response.

Sometime while setting tooltip content dynamically it get freez when moving mouse fastly over element. For this I defined mouseout event on <span> which reintialize the tooltip.

Completed Code

$(document).ready(function(){

 // initialize tooltip
 $( ".content span" ).tooltip({
   track:true,
   open: function( event, ui ) {
   var id = this.id;
   var split_id = id.split('_');
   var userid = split_id[1];
 
   $.ajax({
    url:'fetch_details.php',
    type:'post',
    data:{userid:userid},
    success: function(response){
 
    // Setting content option
    $("#"+id).tooltip('option','content',response);
 
   }
  });
  }
 });

 $(".content span").mouseout(function(){
   // re-initializing tooltip
   $(this).attr('title','Please wait...');
   $(this).tooltip();
   $('.ui-tooltip').hide();
 });

});


5. PHP

Create a new fetch_details.php file.

Select the user detail from users table using POST userid and return the data.

Completed Code

<?php

include "config.php";

$userid = $_POST['userid'];

$select_query = "SELECT * FROM users WHERE id=".$userid;

$result = mysqli_query($con,$select_query);

$html = '<div>';
while($row = mysqli_fetch_array($result)){
 $username = $row['username'];
 $name = $row['name'];
 $gender = $row['gender'];
 $email = $row['email'];

$html .= "<span class='head'>Name : </span><span>".$name."</span><br/>";
 $html .= "<span class='head'>Username : </span><span>".$username."</span><br/>";
 $html .= "<span class='head'>Gender : </span><span>".$gender."</span><br/>";
 $html .= "<span class='head'>Email : </span><span>".$email."</span><br/>";
}
$html .= '</div>';

echo $html;

6. CSS

.container{
 margin: 0 auto;
 width: 30%;
}

.content{
 border: 1px solid black;
 padding: 5px;
 margin-bottom: 5px;
}
.content span{
 width: 250px;
}
.content span:hover{
 cursor: pointer;
}

7. Demo


8. Conclusion

On tooltip open event sends AJAX request to fetch the data and update the tooltip content with the response on successfully callback.

To stop the tooltip from freeze I define mouseout event from where reinitialize the tooltip.

If you know some better solution to solving this problem, let me know in the comment section.

If you found this tutorial helpful then don't forget to share.

Related Post

Spread the love
  • 9
  •  
  •  
  •  
  •  
  •  

10 Comments

  1. syed ather said:

    can we use this code in asp.net

    October 6, 2017
    Reply
  2. jazuly said:

    is that posible to load data if same id?
    i try u code but not load if the id is same.

    January 27, 2018
    Reply
    • Yogesh Singh said:

      Hi jazuly,
      id should be unique otherwise data not load.

      January 27, 2018
      Reply
      • jazuly said:

        ok, but how if i want to add a loading effect up to the data completely loaded.

        January 28, 2018
        Reply
        • Yogesh Singh said:

          In already displaying “Please wait…” message when data loading is in progress.

          If you want to display an image loader or any element on tooltip when loading not completed use beforeSend in $.ajax. Here, is the demo link.

          January 28, 2018
          Reply
  3. Mikel said:

    I don’t understand this sentence:
    $(“#”+id).tooltip(‘option’,’content’,response);
    What means $(“#”+id) ? is this expression correct?

    Thanks

    February 9, 2018
    Reply
    • Yogesh Singh said:

      id variable has id and use in $(“#”+id) to select the element e.g. id=’user_1′, id=’user_2′, etc.

      February 10, 2018
      Reply
  4. Drohjho said:

    Good code!
    These codes will be useful for further displaying the result of php-mariadb query.

    April 15, 2018
    Reply
  5. José Luis Caro Moreno said:

    great job. I wanted to know how to change the width of the pop-up

    Thank you.

    December 10, 2018
    Reply
    • Yogesh Singh said:

      Add following CSS in your file –
      div.ui-tooltip {
      min-width: 400px;
      }
      Update min-width value.

      December 11, 2018
      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *