Solved

Using jQuery tooltipsy with json

Posted on 2013-06-14
2
539 Views
Last Modified: 2013-06-17
Hi experts

I asked a previous question. This is the link to my previous question.
http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/Jquery/Q_28154576.html

So I got a similar example working. This is what I have.

Example 1
Using jQuery tooltipsy with static json file

I have a json file called testEmployees.js
this is the code:

{
"employees" : [ 
    {
        "EmployeeID"   : "1",
        "LastName" : "Davolio",
        "FirstName" : "Nancy",
        "Title" : "Sales Representative"
    },
    {
        "EmployeeID"   : "2",
        "LastName" : "Fuller",
        "FirstName" : "Andrew",
        "Title" : "Vide President Sales"
    },
    {
        "EmployeeID"   : "3",
        "LastName" : "Leverling",
        "FirstName" : "Janet",
        "Title" : "Sales Representative"
    },
    {
        "EmployeeID"   : "4",
        "LastName" : "Peacock",
        "FirstName" : "Margaret",
        "Title" : "Sales Representative"
    },
    {
        "EmployeeID"   : "5",
        "LastName" : "Buchanan",
        "FirstName" : "Steven",
        "Title" : "Sales Manager"
    },
    {
        "EmployeeID"   : "6",
        "LastName" : "Suyama",
        "FirstName" : "Michael",
        "Title" : "Sales Representative"
    },
    {
        "EmployeeID"   : "7",
        "LastName" : "King",
        "FirstName" : "Robert",
        "Title" : "Sales Representative"
    },
    {
        "EmployeeID"   : "8",
        "LastName" : "Callahan",
        "FirstName" : "Laura",
        "Title" : "Inside Sales Coordinator"
    },
    {
        "EmployeeID"   : "9",
        "LastName" : "Dodsworth",
        "FirstName" : "Anne",
        "Title" : "Sales Representative"
    }
          ] 
}

Open in new window


I have a file called tooltipsyjson3.aspx
this is the code:
<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="tooltipsyjson3.aspx.vb" Inherits="tt1.tooltipsyjson3" %>

<!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 runat="server">
    <title></title>
    <%-- CSS Style --%>
<style type="text/css">

span.hastip {
    background:#FFFFFF;
    width:15px;
    height:15px;
    display:inline-block;    
    margin-left:10px;
}

</style>
    <%-- referening jquery library --%>
    <script language="javascript" type="text/javascript" src="Scripts/jquery-1.9.1.js"></script>
    
    <%-- referening the tooltipsy plugin --%>
    <script language="javascript" type="text/javascript" src="Scripts/tooltipsymin.js"></script>
   
    <%-- tooltipsy Function --%>
    <script language="javascript" type="text/javascript">
    
        $(document).ready(function () {

            $('.hastip').tooltipsy({

                content: function ($el, $tip) {
                    var $el = $("#myTestTooltip");
                    var active_tooltip = $el.attr('rel');
                    $el.text="DAHBDGTSHFDH"

                    $.getJSON('testEmployees.js', function (data) {

                        $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>';
                        });
                    });
                    return 'Fallback content';
                },
                css: {
                    'padding': '10px',
                    'max-width': '200px',
                    'color': '#000000',
                    'background-color': '#f5f5f5',
                    'border': '1px solid #e3e3e3'
                }
            });
        });

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>    
        <br />
        <br />
        <br />
        <br />
        <br />
        <br />
        This tooltip gets the first element of the json array<span id= "myTestTooltip" class="hastip" rel="0"><a href="http:www.google.com">tooltipsy</a></span>
    </div>
    </form>
</body>
</html>

Open in new window


When I run my asp page I get this. So when I click on the word tooltipsy the tooltip is correctly bound to my json file.

example 1
So now I'm working on a different example but tooltipsy will get the json data from a .asmx web service.

Example 2
Using jQuery tooltipsy with a json file returned from a Web Service that uses a sql server stored procedure.


For this example I'm using SQL Server 2008, Visual Studio 2010, and VB
I'm using the Employees table from the Northwind database.

I have a Web Service called EmployeeJSONformattedSP.asmx
This Web Service uses a Stored Procedure called GetEmployeesJsonFormatted2

This is the code for GetEmployeesJsonFormatted2:

CREATE PROCEDURE [dbo].[GetEmployeesJsonFormatted2] 

AS
BEGIN
	
SELECT '{' + ' ' + '"' + 'employees' + '"' + ' ' + ':' + ' ' + '[' + ' ' + STUFF((
        SELECT
            ', { "EmployeeID":' + '"' + cast(EmployeeID as varchar(max)) + '"'
            + ',"LastName":"' + LastName + '"'
            + ',"FirstName":' + '"' + cast(FirstName as varchar(max)) + '"'
            + ',"Title":' + '"' + cast(Title as varchar(max)) + '"'
            + ' ' + '}'
        FROM [Northwind].[dbo].[Employees]
        FOR XML PATH(''), TYPE
    ).value('.', 'varchar(max)'), 1, 1, '') + ' ' +  ']' + ' ' +  '}'  AS 'MyString'

	
END

Open in new window


This is the code for my Web Service called EmployeeJSONformattedSP.asmx

When I run the web service in the browser I get this:

my web service
When I click on the GetEmployeesString method I get this:

result of my Web Service
So no I want to create my asp page with the jquery to fetch this string that is formatted as json.

So I created a page called tooltipsyjson4.aspx

This is the code for this page:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="tooltipsyjson4.aspx.vb" Inherits="tt1.tooltipsyjson4" %>

<!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 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 language="javascript" type="text/javascript" src="Scripts/jquery-1.9.1.js"></script>
    
    <%-- referening the tooltipsy plugin --%>
    <script language="javascript" type="text/javascript" src="Scripts/tooltipsymin.js"></script>
   
    <%-- tooltipsy Function --%>
    <script language="javascript" type="text/javascript">
    
        $(document).ready(function () {

            $('.hastip').tooltipsy({

                content: function ($el, $tip) {
                    var $el = $("#myTestTooltip");
                    var active_tooltip = $el.attr('rel');
                    $el.text="DAHBDGTSHFDH"

                    // $.getJSON('testEmployees.js', function (data) {
                    
                    $.getJSON('EmployeeJSONformattedSP.asmx/GetEmployeesString', function (data) {
                    //$.getJSON('EmployeeReturnJSON.asmx/GetEmployeesJSON', function (data) {

                        $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>';
                        });
                    });
                    return 'Fallback content';
                },
                css: {
                    'padding': '10px',
                    'max-width': '200px',
                    'color': '#000000',
                    'background-color': '#f5f5f5',
                    'border': '1px solid #e3e3e3'
                }
            });
        });

    </script>
</head>
<body>
    <form id="form1" 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" rel="0"><a href="http:www.google.com">tooltipsy</a></span>
    </div>
    </form>
</body>
</html>

Open in new window


So when I run my asp page I get this:

example 2 when I run it
When I hover over the word tooltipsy I get this.

Does anyone know where I'm making a mistake that is causing tooltipsy not to bind to the json data correctly?
Is it in my javascript when I call the web service using the $.getJSON function ?

At first I thought my Web Service is formatted wrong so I created this other web service called EmployeeReturnJSON.asmx

This is the code:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web
Imports System.Web.Script.Services
Imports System.Data
Imports System.Data.SqlClient

' 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 EmployeeReturnJSON
    Inherits System.Web.Services.WebService

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

    ' This method returns a Json type.
    <WebMethod()> _
    <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
        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


When I run this web service I get this:

the methods in my web service
Then if I run the GetEmployeesJSON method I get this:

running the GetEmployeesJSON method
Since my 1st Web Service didn't work, I tried this one instead.

But neither one seemed to work.

Can anyone help with Example 2. Where am I making  a mistake?
Example 2 should work just like example 1.
t6.jpg
0
Comment
Question by:maqskywalker
2 Comments
 
LVL 23

Expert Comment

by:Ioannis Paraskevopoulos
ID: 39249978
Hi,

I haven't tried your code, but i would like to make a notice. Your web service is returning an XML and not a JSON, so that is your problem. You could check how to modify it in order to return JSON.

By the way, having answered your other question about tooltipsy, and seen the way you ask questions, i would like to comment that you do a great job asking. Rarely i've seen so specific questions...

Giannis
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39250062
The following work for me, you must use ajax and specify the content-type :

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="tooltipsyjson4.aspx.vb"  %>
<!DOCTYPE >
<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 src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<%-- referening the tooltipsy plugin --%>
<script type="text/javascript" src="http://127.0.0.1/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: 'EmployeeJSONformattedSP.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

Simple EmployeeJSONformattedSP.asmx :
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Web.Script.Services

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class EmployeeJSONformattedSP
    Inherits System.Web.Services.WebService

    <WebMethod()> _
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
    Public Function GetEmployeesString() As String
        Return "{""employees"":[{""EmployeeID"":""1"",""LastName"":""Davolio"",""FirstName"":""Nancy"",""Title"":""Sales Representative""}]}"
    End Function

End Class

Open in new window

0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

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…
Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. 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…

746 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

10 Experts available now in Live!

Get 1:1 Help Now