In the constantly evolving world of web development, creating an immersive and engaging user experience is crucial. One way to achieve this is by utilizing tooltips – a powerful tool that provides additional context and information when users interact with specific elements on a website.
By combining jQuery UI Tooltip with PHP, you can create dynamic tooltips that seamlessly fetch and display data in real-time.
In this article, readers will embark on a journey to explore the fusion of these technologies, discovering how interactive tooltips can captivate and inform users while showcasing data in creative ways. So why wait? Let’s dive into the exciting world of dynamically showcasing data in jQuery UI using PHP!
Table of Content
- Create a Table
- Database Configuration file
- HTML – Create Layout
- jQuery – Initialize tooltip and load data
- PHP – Return Tooltip data
- Add CSS
- Demo
- Conclusion
1. Create a Table
I am using users
table in the 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 );
2. Database Configuration file
Create a config.php
for the database connection.
<?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 – Setup Tooltip Layout
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.
Store userid in data-id
attribute.
You can define any default value in the title
attribute.
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <script src='script.js' type='text/javascript'></script> <div class='container'> <div class='content'> <span title='Please wait..' data-id='1' id='user_1'>Yogesh Singh</span> </div> <div class='content'> <span title='Please wait..' data-id='2' id='user_2'>Sonarika Bhadoria</span> </div> <div class='content'> <span title='Please wait..' data-id='3' id='user_3'>Vishal Sahu</span> </div> <div class='content'> <span title='Please wait..' data-id='4' id='user_4'>Sunil</span> </div> </div>
4. jQuery – Initialize tooltip and load data
Create script.js
file.
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 from
data-id
attribute and assign to theuserid
variable. Send the AJAX request and pass the userid asdata
. On successful callback update thecontent
option with the response.
NOTE – 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.
$(document).ready(function(){ // initialize tooltip $( ".content span" ).tooltip({ track:true, open: function( event, ui ) { var id = this.id; var userid = $(this).attr('data-id'); $.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 – Return Tooltip data
Create fetch_details.php
file.
Assign POST userid
value to a variable. Execute a SELECT query on users
table where id matches with $userid
. Loop on the fetched data and create a HTML layout that has user details.
Return $html
variable.
<?php include "config.php"; $userid = 0; if(isset($_POST['userid'])){ $userid = mysqli_real_escape_string($con,$_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. Add 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
Enhance user interaction and display personalized info in a visually appealing way by adding dynamic tooltips to your web apps with jQuery UI and PHP. PHP’s strength lies in fetching content on-the-go, and jQuery UI Tooltip’s flexibility lets you customize tooltips to suit your app’s requirements.
This article outlines a step-by-step implementation to harness the potential of PHP and jQuery UI Tooltip for creating interactive tooltips that offer real-time data to users. It is important to prioritize security measures by validating user inputs and cleaning data for ensuring an application that is secure.
If you found this tutorial helpful then don't forget to share.
can we use this code in asp.net
yes
is that posible to load data if same id?
i try u code but not load if the id is same.
Hi jazuly,
id should be unique otherwise data not load.
ok, but how if i want to add a loading effect up to the data completely loaded.
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.
I don’t understand this sentence:
$(“#”+id).tooltip(‘option’,’content’,response);
What means $(“#”+id) ? is this expression correct?
Thanks
id
variable has id and use in $(“#”+id) to select the element e.g. id=’user_1′, id=’user_2′, etc.Good code!
These codes will be useful for further displaying the result of php-mariadb query.
great job. I wanted to know how to change the width of the pop-up
Thank you.
Add following CSS in your file –
div.ui-tooltip {
min-width: 400px;
}
Update min-width value.
Hi Yogesh,
I add the below code
div.ui-tooltip {
min-width: 800px;
}
to style.css file
but the width of the pop-up is the same size as before adding this code!
Where is my problem?
This is a great tutorial. However I can’t manage to trigger the open event. The tooltip from JQuery UI is shown, but on debugging the browser the open: function( event, ui ) is not being triggered.
My selector matches the elements class (there a lot of elements with the same class)
$( “.c-hex-grid__media” ).tooltip({….
Any ideas appreciated!
The mouseout IS triggering though…
$(“.c-hex-grid__media”).mouseout(function(){
Can you share me your code at makitweb@gmail.com so I can check it?
Thanks, I’ve emailed you
I’ve tried copying and running your code, unfortunately only display the “please wait ..” message only. why?
please ignore previous comments. your code works perfectly but what if I wanted to replace userid from an increment number to a user id like a matric number or ect
my problem solved. tq so much
it does’t work, it’s the same code ,why?
Hi Abdallah,
Is any error you are getting?
Hi, the script looks fine, thanks a lot. But I have the problem, that the tooltip starts working on the second mouseover. After the tooltip has been shown first, it works on every mouseover.
Firefox-Console does not display any errors.
Hi Rudolf,
Can you share me the link at makitweb@gmail.com so I can look at it?
hi can you send me the code also. fpatrick.garcia92@gmail.com
Hi Patrick,
The download link is available in the tutorial.
Uncaught TypeError: data[option] is not a function