Jacob Tomlinson

11

Sep

2012

How to query a database with AJAX and display as a tooltip

by under Web Development on 11 Sep 2012

This post began as an answer on Stack Overflow to a question on ‘How to query a database with AJAX and display as a tooltip‘. I have put the answer here for future reference.

The original question asked for more information on the steps :

  • User clicks on a link
  • Variable passed to external file using AJAX
  • External file uses variable to query MySQL database
  • Query result appears in tooltip
and so I have turned each step into a heading and added content to each to describe the process.

User clicks on a link

So the first thing you need is a bit of front end code which tells a link to make an ajax request and not an actual link. I would recommend that you use jQuery to do the hard work for you so you will first need to include the jQuery script in your page if you haven’t already, to do this add this line to the head of your HTML file.

Next you will need to give the link a class so for example your link may look like

You will see that the link will be to the ajax page which is going to provide the data, you are passing a variable on to that page called var via GET which we will come to later and you also have the class set to “ajax_link” which we will use to reference the link from jQuery.

Now you will need to write some jQuery to handle the link. To do this you will need to open up a <script language=”javascript”> tag at the end of your body and put some code along the lines of:

I will come back to the tooltip code later on.

Variable passed to external file using AJAX
Now we are going to need to create the PHP file ajax.php, this file will need to connect to the database and make any queries necessary. First I will start the file and get the variable from the GET. See the code below.

This will create the variable $var and it will contain the value ‘value’ as was set in the above HTML link. You will probably want to escape the value, do some validation to protect yourself from injection but I will not cover that here.
UPDATE: Added most basic string escape function to stop people from copying and pasting and opening themselves up to injection but I would recommend seeing this stack overflow answer for more information.

External file uses variable to query MySQL database
Next you will want to connect to and query the database and then echo what ever it is that you have returned. Here is some code for returning the value of column ‘information’ from a table called ‘data_table’ where some value equals your $var.

For more information on querying a database please see this tutorial.

Query result appears in tooltip
Once you have both of these pages set up the first page will send some value to the ajax page, the ajax page will echo the corresponding information from the database which will be received by the first page in the JavaScript variable html.

The final stage of this is now to display the returned text as a tooltip. First it may be a good idea to test that your pages are working and one easy way to do this is to display an alert with the returned information in (you could also log to the console). You would do this by adding some code to the ajax .done function like so:

Once you have done this you should be able to open up the page, click the link and you should see an alert box pop up showing the required text. If there is nothing after the ‘text:’ in the alert then something has gone wrong and you may want to check the code is correct. If it has succeeded then continue on to displaying the tooltip.

There are many available jQuery tooltip plugins one of which is called qTip. This will allow you to create the tooltips and display them when clicking on them. You will need to download the JavaScript file and related CSS for the tooltips and then add some code into the .done function to create and display the tooltip.

To add qTip to your page place visit the qTip site and download the latest version of the js and the css. Then you must reference the files in the head like this:

and the js like this:

This assumes that the css and js files are in the same folder as your index page, if they aren’t please amend these links to point to where you have put those files.

Now all you need to add to the .done function is the following:

This code will create a qTip containing whatever was returned from your AJAX request. Then once the tooltip has been created it will toggle it to show the tooltip initially once clicked. Then the tooltip will show/hide when you hover on/off.

For more information on styling a qTip see their website.


Written by

is a unix system administrator by day and a website and app developer by night. With experience in RHEL and OS X administration, HTML5, CSS3, JavaScript, jQuery, PHP, Python, MySQL, CodeIgniter, Wordpress and much more. When he is not tapping away at his keyboard you can usually find him making music, gaming or spending time with his wonderful fiancée.


10 comments

  1. hemanth

    How can do the same thing in jsp instead of using php. Can you please give the solution

    • Jacob Tomlinson

      @hemanth
      I know nothing about JSP but based on information found here, here and here I’ve put together the following code. It may not work but it should get you started.

  2. hemanth

    Thank you very much. I have one more problem
    While testing my page as you suggested (using alert box), the alert box is displaying entire html page instead of the text. Can you suggest me something on this problem

  3. jordan mcdonald

    Cool. I am using an ASPX page and the entire HTML of the page is showing up in the qtip.
    I just want a few bits of data to display.

    Should I be using a code behind page instead of ASPX which is an HTML based page?
    My thought was that just the body of the aspx page would return but the entire set of HTML is returning.

    thanks

    • jordan mcdonald

      I got it working I believe! thanks

      • Jacob Tomlinson

        Great. Perhaps you could share how you got it working?

  4. Peter Snow

    Hi Jacob,

    Nice site and useful tutorial. I was doing ok until I dropped in this:

    $(this).qtip({
    content : {
    text : html
    },
    });
    $(this).qtip(‘toggle’, true);

    I removed the alert (which was displaying text from the server ok), but I got the following error:

    Uncaught TypeError: Cannot read property ‘width’ of undefined g=mainJS:7078
    getWidthOrHeight g=mainJS:7078
    jQuery.cssHooks.(anonymous function).get g=mainJS:7156
    jQuery.extend.css g=mainJS:6879
    (anonymous function) g=mainJS:9566
    jQuery.extend.access g=mainJS:877
    jQuery.fn.(anonymous function) g=mainJS:9541
    C.reposition g=mainJS:9774
    C.toggle g=mainJS:9774
    (anonymous function) g=mainJS:9774
    (anonymous function) g=mainJS:1192
    fire g=mainJS:1037
    self.add g=mainJS:1083
    (anonymous function) g=mainJS:1191
    jQuery.extend.each g=mainJS:648
    (anonymous function) g=mainJS:1187
    jQuery.extend.Deferred g=mainJS:1248
    promise.then g=mainJS:1186
    C.render g=mainJS:9774
    C.toggle g=mainJS:9774
    (anonymous function) g=mainJS:9774
    jQuery.extend.each g=mainJS:648
    jQuery.fn.jQuery.each g=mainJS:270
    o.fn.qtip g=mainJS:9774
    (anonymous function) g=mainJS:10130
    fire g=mainJS:1037
    self.fireWith g=mainJS:1148
    done g=mainJS:8074
    callback g=mainJS:8598

    The above was from the Chromium Javascript console.

    Firefox gives the following error:
    Error: NS_ERROR_FAILURE: Component returned failure code: 0×80004005 (NS_ERROR_FAILURE) [nsIDOMWindow.getComputedStyle]
    Source File: http://snowweb.net/min/g=mainJS
    Line: 6926

    The page I’m working on can be found at http://snowweb.net/pages/web-design.php

    Could this be due to the fact that I’m using a dynamic width template, based on ‘em’s rather than setting a static width? If you think this could be the case, can you think of a work-around without going back to a fixed width template?

    Thanks.

  5. Gaetano

    I have a need to use the tool tip with simple JS and PHP. Do you have an example that hovers the link and the JS fires off to query a database in PHP (i guess JSON) then returns the answer to the correct link. Each link hovered will need to fire off a query and return. Can this be done and shown to me?

    I did not want to introduce new stuff like Jquery and include my database connection information in the query. I am trying to do this on the server.
    Any help with an example would be nice.
    I am using the dynamic drive dot com tool tip example as a guide that reads a file or has the data hard coded. I wanted to make it dynamic based on the Link ID of the record displayed. Then go fetch additional details based on the hover.

    Any help on this would be appreciated.

    • Jacob Tomlinson

      Why is it that you’re opposed to using jQuery? It will make your task much easier.

Leave a Reply

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


6 − three =

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">