Solved

jquery plugin tooltipsy fetching json with ajax function

Posted on 2013-06-17
1
1,081 Views
Last Modified: 2013-06-18
Hi experts,

This is a follow up on a question I had previously asked.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28157999.html

This is a question on asp.net using jquery plugin called tooltipsy: http://tooltipsy.com

I'm using Visual Studio 2010 and VB as the language.
I'm using the Employees table from the Northwind Sql Server database.

So this is what I currently have.

My visual studio  project directory looks like this:

my directory
I'm using this version of the jquery library  jquery-1.10.0.min.js
which can be downloaded here: http://jquery.com/download

This is the code for the tooltipsy plugin tooltipsymin.js :

/* tooltipsy by Brian Cray
* Lincensed under GPL2 - http://www.gnu.org/licenses/gpl-2.0.html
* Option quick reference:
* - alignTo: "element" or "cursor" (Defaults to "element")
* - offset: Tooltipsy distance from element or mouse cursor, dependent on alignTo setting. Set as array [x, y] (Defaults to [0, -1])
* - content: HTML or text content of tooltip. Defaults to "" (empty string), which pulls content from target element's title attribute
* - show: function(event, tooltip) to show the tooltip. Defaults to a show(100) effect
* - hide: function(event, tooltip) to hide the tooltip. Defaults to a fadeOut(100) effect
* - delay: A delay in milliseconds before showing a tooltip. Set to 0 for no delay. Defaults to 200
* - css: object containing CSS properties and values. Defaults to {} to use stylesheet for styles
* - className: DOM class for styling tooltips with CSS. Defaults to "tooltipsy"
* - showEvent: Set a custom event to bind the show function. Defaults to mouseenter
* - hideEvent: Set a custom event to bind the show function. Defaults to mouseleave
* Method quick reference:
* - $('element').data('tooltipsy').show(): Force the tooltip to show
* - $('element').data('tooltipsy').hide(): Force the tooltip to hide
* - $('element').data('tooltipsy').destroy(): Remove tooltip from DOM
* More information visit http://tooltipsy.com/
*/
;(function(a){a.tooltipsy=function(c,b){this.options=b;this.$el=a(c);this.title=this.$el.attr("title")||"";this.$el.attr("title","");this.random=parseInt(Math.random()*10000);this.ready=false;this.shown=false;this.width=0;this.height=0;this.delaytimer=null;this.$el.data("tooltipsy",this);this.init()};a.tooltipsy.prototype={init:function(){var e=this,d,b=e.$el,c=b[0];e.settings=d=a.extend({},e.defaults,e.options);d.delay=+d.delay;if(typeof d.content==="function"){e.readify()}if(d.showEvent===d.hideEvent&&d.showEvent==="click"){b.toggle(function(f){if(d.showEvent==="click"&&c.tagName=="A"){f.preventDefault()}if(d.delay>0){e.delaytimer=window.setTimeout(function(){e.show(f)},d.delay)}else{e.show(f)}},function(f){if(d.showEvent==="click"&&c.tagName=="A"){f.preventDefault()}window.clearTimeout(e.delaytimer);e.delaytimer=null;e.hide(f)})}else{b.bind(d.showEvent,function(f){if(d.showEvent==="click"&&c.tagName=="A"){f.preventDefault()}e.delaytimer=window.setTimeout(function(){e.show(f)},d.delay||0)}).bind(d.hideEvent,function(f){if(d.showEvent==="click"&&c.tagName=="A"){f.preventDefault()}window.clearTimeout(e.delaytimer);e.delaytimer=null;e.hide(f)})}},show:function(i){if(this.ready===false){this.readify()}var b=this,f=b.settings,h=b.$tipsy,k=b.$el,d=k[0],g=b.offset(d);if(b.shown===false){if((function(m){var l=0,e;for(e in m){if(m.hasOwnProperty(e)){l++}}return l})(f.css)>0){b.$tip.css(f.css)}b.width=h.outerWidth();b.height=h.outerHeight()}if(f.alignTo==="cursor"&&i){var j=[i.clientX+f.offset[0],i.clientY+f.offset[1]];if(j[0]+b.width>a(window).width()){var c={top:j[1]+"px",right:j[0]+"px",left:"auto"}}else{var c={top:j[1]+"px",left:j[0]+"px",right:"auto"}}}else{var j=[(function(){if(f.offset[0]<0){return g.left-Math.abs(f.offset[0])-b.width}else{if(f.offset[0]===0){return g.left-((b.width-k.outerWidth())/2)}else{return g.left+k.outerWidth()+f.offset[0]}}})(),(function(){if(f.offset[1]<0){return g.top-Math.abs(f.offset[1])-b.height}else{if(f.offset[1]===0){return g.top-((b.height-b.$el.outerHeight())/2)}else{return g.top+b.$el.outerHeight()+f.offset[1]}}})()]}h.css({top:j[1]+"px",left:j[0]+"px"});b.settings.show(i,h.stop(true,true))},hide:function(c){var b=this;if(b.ready===false){return}if(c&&c.relatedTarget===b.$tip[0]){b.$tip.bind("mouseleave",function(d){if(d.relatedTarget===b.$el[0]){return}b.settings.hide(d,b.$tipsy.stop(true,true))});return}b.settings.hide(c,b.$tipsy.stop(true,true))},readify:function(){this.ready=true;this.$tipsy=a('<div id="tooltipsy'+this.random+'" style="position:fixed;z-index:2147483647;display:none">').appendTo("body");this.$tip=a('<div class="'+this.settings.className+'">').appendTo(this.$tipsy);this.$tip.data("rootel",this.$el);var c=this.$el;var b=this.$tip;this.$tip.html(this.settings.content!=""?(typeof this.settings.content=="string"?this.settings.content:this.settings.content(c,b)):this.title)},offset:function(b){return this.$el[0].getBoundingClientRect()},destroy:function(){if(this.$tipsy){this.$tipsy.remove();a.removeData(this.$el,"tooltipsy")}},defaults:{alignTo:"element",offset:[0,-1],content:"",show:function(c,b){b.fadeIn(100)},hide:function(c,b){b.fadeOut(100)},css:{},className:"tooltipsy",delay:200,showEvent:"mouseenter",hideEvent:"mouseleave"}};a.fn.tooltipsy=function(b){return this.each(function(){new a.tooltipsy(this,b)})}})(jQuery);

Open in new window



So I have a Web Service called EmployeesWebService.asmx

This is the code for it:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web
Imports System.Web.Script.Services
Imports System.Collections.Generic
Imports System.Runtime.Serialization
Imports System.IO
Imports System.Text

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class EmployeesWebService
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    Public Function HelloWorld() As String
        Return "Hello World"
    End Function

    <WebMethod(Description:="Returns the JSON format representation of a table as a string")> _
    Public Function GetEmployeesString() As String

        Dim constring As String = "Data Source=FCOE-DPN1TR1;Initial Catalog=Northwind;Integrated Security=True"

        Dim conn As SqlConnection
        Dim comm As SqlCommand
        conn = New SqlConnection(constring)
        conn.Open()

        comm = New SqlCommand()
        comm.Connection = conn
        comm.CommandType = System.Data.CommandType.StoredProcedure
        comm.CommandText = "GetEmployeesJsonFormatted"
        'comm.Parameters.AddWithValue("@EmployeeID", EmployeeID)

        Dim dtTable As New DataTable

        Try
            'Executes a Transact-SQL statement against the connection and returns the number of rows affected.
            Dim reader As SqlDataReader = comm.ExecuteReader()

            If reader.Read() Then ' Used If since you only have 1 row being returned.
                '  If you select more than one row, then you'll want a loop instead

                'Dim queryResult As String = reader("FirstName").ToString() + " " + reader("LastName").ToString() + " | " + reader("BirthDate").ToString() + " | " + reader("City").ToString()
                Dim queryResult As String = reader("MyString").ToString()

                Return queryResult
            End If

        Catch ex As Exception
            Throw ex
        Finally
            conn.Close()
            conn.Dispose()
        End Try

        Return String.Empty

    End Function


    ' This method returns a Json type.
    <WebMethod(Description:="Returns employees table as JSON data")> _
    <ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json)> _
    Public Function GetEmployeesJSON() As List(Of Employee)
        'Dim reports As New List(Of ModelReport.Report)()
        Dim reports As New List(Of Employee)()

        'Dim connectionString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
        Dim connectionString As String = "Data Source=FCOE-DPN1TR1;Initial Catalog=Northwind;Integrated Security=True"

        Using connection As New SqlConnection(connectionString)
            Using command As SqlCommand = connection.CreateCommand
                Dim sql As String = "SELECT EmployeeID, LastName, FirstName, Title FROM Employees"
                connection.Open()

                command.CommandText = sql
                Using reader As SqlDataReader = command.ExecuteReader()
                    While reader.Read()
                        'Dim report As New ModelReport.Report()
                        Dim report As New Employee()
                        report.EmployeeID = reader("EmployeeID").ToString()
                        report.LastName = reader("LastName").ToString()
                        report.FirstName = reader("FirstName").ToString()
                        report.Title = reader("Title").ToString()

                        reports.Add(report)
                    End While
                End Using
            End Using
        End Using

        Return reports
    End Function


End Class

Public Class Employee
    ' Integer type
    Private privateEmployeeID As String
    Public Property EmployeeID() As String
        Get
            Return privateEmployeeID
        End Get
        Set(ByVal value As String)
            privateEmployeeID = value
        End Set
    End Property
    ' String type
    Private privateLastName As String
    Public Property LastName() As String
        Get
            Return privateLastName
        End Get
        Set(ByVal value As String)
            privateLastName = value
        End Set
    End Property
    ' String type
    Private privateFirstName As String
    Public Property FirstName() As String
        Get
            Return privateFirstName
        End Get
        Set(ByVal value As String)
            privateFirstName = value
        End Set
    End Property
    ' String type
    Private privateTitle As String
    Public Property Title() As String
        Get
            Return privateTitle
        End Get
        Set(ByVal value As String)
            privateTitle = value
        End Set
    End Property
End Class

Open in new window


So when I run my web service in the browser I get this list of methods:

List of methods in my Web Service
If I click on the GetEmployeesString method I get this:

GetEmployeesString method
If I click on the GetEmployeesJSON method I get this:

GetEmployeesJSON method


So now that I have created my Web Service I'm creating two tooltipsy examples.
Example 1 is using the GetEmployeesString method and Example 2 is using the GetEmployeesJSON method

Example 1: Using the GetEmployeesString method

So I created a page called EmployeesJSONFormattedTT.aspx

This is the code for it:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EmployeesJSONFormattedTT.aspx.vb" Inherits="NWEmployees.EmployeesJSONFormattedtt1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<%-- CSS Style --%>
<style type="text/css">
.TestText1 {font-family: Arial; color: #FF0000; font-size: 12px; font-weight: normal;}
span.hastip {
    background:#FFFFFF;
    width:15px;
    height:15px;
    display:inline-block;    
    margin-left:10px;
}
</style>
<%-- referening jquery library --%>
<script type="text/javascript" src="Scripts/jquery-1.10.0.min.js"></script>
<%-- referening the tooltipsy plugin --%>
<script type="text/javascript" src="Scripts/tooltipsymin.js"></script>
<%-- tooltipsy Function --%>
<script type="text/javascript">
    $(document).ready(function () {
        $('.hastip').tooltipsy({
            content: function ($el, $tip) {
                var $el = $("#myTestTooltip");
                var active_tooltip = $el.data('rel');
                $el.text = "DAHBDGTSHFDH"
                $.ajax({
                    url: 'EmployeesWebService.asmx/GetEmployeesString',
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: "{}",
                    dataType: "json",
                    success: function (data) {
                        data = $.parseJSON(data.d);
                        $tip.html(function () {
                            var EmployeeIDtext = data.employees[active_tooltip].EmployeeID;
                            var LastNametext = data.employees[active_tooltip].LastName;
                            var FirstNametext = data.employees[active_tooltip].FirstName;
                            var Titletext = data.employees[active_tooltip].Title;
                            return '<div>' + 'EmployeeID:' + ' ' + EmployeeIDtext + ' ' + '<br/>' + 'LastName:' + ' ' + LastNametext + '<br/>' + 'FirstName:' + ' ' + FirstNametext + '<br/>' + 'Title:' + ' ' + Titletext + '</div>';
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR + "\n" + textStatus + "\n" + errorThrown);
                    }
                });

                return 'Fallback content';
            },
            css: {
                'padding': '10px',
                'max-width': '200px',
                'color': '#000000',
                'background-color': '#f5f5f5',
                'border': '1px solid #e3e3e3'
            }
        });
    });
</script>
</head>
<body>
<form id="form2" runat="server">
<div>    
<br />
<br />
<br />
<br />
<br />
<br />
This tooltip gets the first element of the json array<span id= "myTestTooltip" data-url='employees' class="hastip" data-rel="0" ><a href="http:www.google.com">tooltipsy</a></span>
</div>
</form>
</body>
</html>

Open in new window


When I run this page I get this.
If I mouse over the word tooltipsy the tool tip works great!
This example works as intended. So now I want to do example 2.

tooltipsy using GetEmployeesString method  (string data)

Example 2: Using the GetEmployeesJSON method


This is the example I'm having trouble with.

I'm having trouble writing the correct tooltipsy syntax in the success: function of my $.ajax method

Since GetEmployeesJSON method returns json data I figured out how to fetch this type of json data  like shown in this example:  FetchEmployeesJSONdata.aspx

This is the code for it:  

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="FetchEmployeesJSONdata.aspx.vb" Inherits="NWEmployees.FetchEmployeesJSONdata" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>example fetching JSON data using Ajax function</title>

    <!-- jQuery library reference. Latest is always referenced from jQuery's CDN. -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "EmployeesWebService.asmx/GetEmployeesJSON",
                beforeSend: function () {
                    $("#teamemployees").html("Loading...");
                },
                timeout: 10000,
                error: function (xhr, status, error) {
                    alert("Error: " + xhr.status + " - " + error);
                },
                data: "{}",
                dataType: "json",
                success: function (data) {
                    $("#teamemployees").html("");
                    $.each(data, function () {
                        $.each(this, function (key, value) {
                            $("#teamemployees").append(
                                "EmployeeID: " + value.EmployeeID + "<br>" +
                                "LastName: " + value.LastName + "<br>" +
                                "FirstName: " + value.FirstName + "<br>" +
                                "Title: " + value.Title + "<br><br>"
                            );
                        });
                    });
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">

<div id="teamemployees"></div>

    </form>
</body>
</html>

Open in new window


When I run this page I get this

fetching json data from my GetEmployeesJSON method using $.Ajax method
So in this example, my method is working correctly and I am able to fetch it on a simple html page

My problem is fetching it correctly withing my tooltipsy function.

So I have a page called EmployeesJSONdataTT.aspx

This is the code I have so far:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EmployeesJSONdataTT.aspx.vb" Inherits="NWEmployees.EmployeesJSONdataTT" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<%-- CSS Style --%>
<style type="text/css">
.TestText1 {font-family: Arial; color: #FF0000; font-size: 12px; font-weight: normal;}
span.hastip {
    background:#FFFFFF;
    width:15px;
    height:15px;
    display:inline-block;    
    margin-left:10px;
}
</style>
<%-- referening jquery library --%>
<script type="text/javascript" src="Scripts/jquery-1.10.0.min.js"></script>
<%-- referening the tooltipsy plugin --%>
<script type="text/javascript" src="Scripts/tooltipsymin.js"></script>
<%-- tooltipsy Function --%>
<script type="text/javascript">
    $(document).ready(function () {
        $('.hastip').tooltipsy({
            content: function ($el, $tip) {
                var $el = $("#myTestTooltip");
                var active_tooltip = $el.data('rel');
                $el.text = "DAHBDGTSHFDH"
                $.ajax({
                    url: 'EmployeesWebService.asmx/GetEmployeesJSON',
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    data: "{}",
                    dataType: "json",
                    success: function (data) {
                        data = $.parseJSON(data.d);
                        $tip.html(function () {
                            var EmployeeIDtext = data.employees[active_tooltip].EmployeeID;
                            var LastNametext = data.employees[active_tooltip].LastName;
                            var FirstNametext = data.employees[active_tooltip].FirstName;
                            var Titletext = data.employees[active_tooltip].Title;
                            return '<div>' + 'EmployeeID:' + ' ' + EmployeeIDtext + ' ' + '<br/>' + 'LastName:' + ' ' + LastNametext + '<br/>' + 'FirstName:' + ' ' + FirstNametext + '<br/>' + 'Title:' + ' ' + Titletext + '</div>';
                        });
                    },
                    error: function (jqXHR, textStatus, errorThrown) {
                        alert(jqXHR + "\n" + textStatus + "\n" + errorThrown);
                    }
                });

                return 'Fallback content';
            },
            css: {
                'padding': '10px',
                'max-width': '200px',
                'color': '#000000',
                'background-color': '#f5f5f5',
                'border': '1px solid #e3e3e3'
            }
        });
    });
</script>
</head>
<body>
<form id="form2" runat="server">
<div>    
<br />
<br />
<br />
<br />
<br />
<br />
This tooltip gets the first element of the json array<span id= "myTestTooltip" data-url='employees' class="hastip" data-rel="0" ><a href="http:www.google.com">tooltipsy</a></span>
</div>
</form>
</body>
</html>

Open in new window


When I run this page I get this:
example 2 tooltipsy not working
My tooltipsy is not fetching the GetEmployeesJSON method correctly within the success function.

I believe my issue is in the section highlighted in red in this pic:

code section where I'm having problems
Can anyone help? How should I properly call my columns?
0
Comment
Question by:maqskywalker
1 Comment
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39254830
line 38, replace : data = $.parseJSON(data.d);
by : data = $.parseJSON(data.d)[0];

Do you have a link to see the page? Or can you setup one?
0

Featured Post

Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

Join & Write a Comment

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

19 Experts available now in Live!

Get 1:1 Help Now