Solved

correctly fetching json data from Web Service json array

Posted on 2013-06-11
1
424 Views
Last Modified: 2013-06-18
Hi experts,

I need help in an example i'm working on. Below I'm describing two examples.
Example 2 is the one I need help on.
Example 1 works correctly and my example 2 is a modification of example 1.

I'm using Visual Studio 2010, SQL Server 2008, VB as the code language and jquery.

So i saw this link and I worked on this example:

jQuery Tutorial: Build Hovercards for your Website
http://time2hack.com/2013/03/jquery-tutorial-build-hovercards-for-your-website.html

Example 1

So for my example these are the steps I did:

Step 1         Create JSON file

Step 2         Create ASP.NET page, Add CSS to ASP.NET page , Add JavaScript that fetches JSON file

Step 3      Run Application

So now this is what I did.


Step 1         Create JSON file


I created a JSON file called hover_data_products.json this is the code in this file:

{
	"TeamID_01" : {
	    "product_id" : "1", 
		"product_name" : "Chai", 
		"quantity_per_unit" : "10 boxes x 20 bags", 
		"unit_price" : "18.00"
		} ,
	"TeamID_02" : {
	    "product_id" : "2", 
		"product_name" : "Chang", 
		"quantity_per_unit" : "24 - 12 oz bottles", 
		"unit_price" : "19.00"
		}
}

Open in new window



Step 2         Create ASP.NET page

So now I create a asp.net called TestProducts.aspx.

I placed my JSON file in the same directory as this asp.net page.
This is what my visual studio directory looks like:

example 1 application directory
This is the code for TestProducts.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="TestProducts.aspx.vb" Inherits="TestProducts" %>

<!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>
<style type="text/css">
.link{
background: #222;
background: -moz-linear-gradient(#252525, #0A0A0A) ;
background: -o-linear-gradient(#252525, #0A0A0A);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#252525), to(#0A0A0A));
background: -webkit-linear-gradient(#252525, #0A0A0A);
-webkit-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
-moz-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
color:#fff;
padding: 8px 10px;
text-decoration: none;
font-weight: normal;
font-size: 18px;
font-family: Arial,Verdana;
word-spacing: 1px;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
-o-border-radius: 4px;
-ms-border-radius: 4px;
}
.link:hover{
background:#62ABD8 !important;
background: -moz-linear-gradient(#80BADE, #62ABD8) ;
background: -o-linear-gradient(#80BADE, #62ABD8);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#80BADE), to(#62ABD8));
background: -webkit-linear-gradient(#80BADE, #62ABD8);
-webkit-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
-moz-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
}
.link:active{
background:#62ABD8 !important;
background: -moz-linear-gradient(#80BADE, #62ABD8) ;
background: -o-linear-gradient(#80BADE, #62ABD8);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#80BADE), to(#62ABD8));
background: -webkit-linear-gradient(#80BADE, #62ABD8);
-webkit-box-shadow: inset rgba(0, 0, 0, 0.4) 0px 1px 2px;
-moz-box-shadow: inset rgba(0, 0, 0, 0.4) 0px 1px 2px;
box-shadow: inset rgba(0, 0, 0, 0.4) 0px 1px 2px;
}
</style>
<style type='text/css'>
.links{
    color: #555;
    padding: 5px;
    cursor: pointer;
}
.hovercard {
    display: none;
    position: absolute;
    width:300px;
padding:3px;
    height: 150px;
    border:1px solid #aaa;
    border-radius: 3px;
    background-color: #fff;
    -webkit-box-shadow:  rgba(0, 0, 0, 0.4) 0px 3px 4px;
-moz-box-shadow:  rgba(0, 0, 0, 0.4) 0px 3px 4px;
box-shadow:  rgba(0, 0, 0, 0.4) 0px 3px 4px;
}
.hovercard:before {
   content: "";
   position: absolute;
   bottom: 100%;
   left: 20px;
   border-bottom: 20px solid black;
   border-bottom-color: inherit; 
   border-left: 20px solid transparent;
   border-right: 20px solid transparent; 
}
.hovercard h3{
    font-family: Verdana, Georgia;
    border-bottom: 1px dashed #ccc;
}
.hovercard a{
    text-decoration: none;
    cursor: pointer;
    border-bottom: 1px dashed #eee;
}
</style>
<script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script>
<script type='text/javascript'>
    $(document).ready(function (e) {
        $('span[rel="hovercard"]').hover(
        function (e) {
            position = $(this).position();
            x = $(this).data('url');
            $.getJSON('hover_data_products.json', function (data) {
                $('.hovercard').html('</h3>Product ID : ' + eval('data.' + x + '.product_id') + '<br/></h3>Product Name : ' + eval('data.' + x + '.product_name') + '<br/></h3>Quantity Per Unit : ' + eval('data.' + x + '.quantity_per_unit') + '<br/></h3>Unit Prie : ' + eval('data.' + x + '.unit_price'))
            })
            $('.hovercard').show().css('top', position.bottom).css('left', position.left);
            //Mouse In code
        },
        function (e) {
            $('.hovercard').hide();
            //Mouse Out code
            $('hovercard').html('');
        });
    });
</script>
</head>
<body>
    <form id="form1" runat="server">
<div style="width:100%;text-align:center;margin:0 auto;">
    <div><center><h1>Time to Hack</h1>
        <h3><a href="" class="link">Back to Tutorial</a></h3></center>
    </div>
    <hr>
    <br/>
<div>Hover These Texts</div><br>
<span rel='hovercard' data-url='TeamID_01' class="links">Chai</span>|<span rel='hovercard' data-url='TeamID_02' class="links">Chang</span>
</div>
<br>
<br>
 
<div class="hovercard"></div>
  
<style type="text/css">
#pankaj{
    display: block;
    width:728;
    height:90;
    line-height: 50px;
    font-weight: 25px;
    text-align: center;
    margin: 0 auto;
    border:1px solid #ccc;
    margin-top: 10px;
    -webkit-transition: 2000ms;
}
#pankaj:hover{
    transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
-webkit-transition: 2000ms;
-moz-transform: rotateY(180deg);
-moz-transition: 2000ms;
-ms-transform: rotateY(180deg);
-ms-transition: 2000ms;
-o-transform: rotateY(180deg);
-o-transition: 2000ms;
 
}
    .style1
    {
        width: 60%;
    }
    .style2
    {
        width: 163px;
        text-align: center;
    }
    .style3
    {
        width: 437px;
    }
</style> 

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

Open in new window


This is the code for TestProducts.aspx.vb

Partial Class TestProducts
    Inherits System.Web.UI.Page

End Class

Open in new window


Step 3      Run Application

So now when I run TestProducts.aspx , I get the following:

example 1 run
So the example works correctly.  In the asp page I'm successfully fetching the json data from the json file called hover_data_products.json  that is found in the same app directory.


Example 2

So now I'm creating example 2. This example should produce the same result as example 1 but in this example instead of fetching the data from a json file that is in the application directory. I'm going to have a Web Service that returns json data from a sql server table.

So here are the steps:

Step 1          Create the SQL Server Table

Step 2         Create Web Service that outputs JSON array

Step 3          Create ASP.NET page, Add CSS to ASP.NET page , Add JavaScript that fetches JSON file

Step 4      Run Application



Step 1          Create the SQL Server Table

So first I created a table called Drinks

This is the code to create the table:

CREATE TABLE [dbo].[Drinks](
	[product_id] [int] NULL,
	[product_name] [varchar](50) NULL,
	[quantity_per_unit] [varchar](50) NULL,
	[unit_price] [varchar](50) NULL
) ON [PRIMARY]
GO
INSERT [dbo].[Drinks] ([product_id], [product_name], [quantity_per_unit], [unit_price]) VALUES (1, N'Chai', N'10 boxes x 20 bags', N'18.00')
INSERT [dbo].[Drinks] ([product_id], [product_name], [quantity_per_unit], [unit_price]) VALUES (2, N'Chang', N'24 – 12 oz bottles', N'19.00')

Open in new window


So after I created the table , it looks like this:

Drinks table

Step 2         Create Web Service that outputs JSON array

So now I created a .asmx Web Service called ProductsWebService.asmx

This is the code for it:

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel
Imports System.Web
Imports System.Web.Script.Services
Imports System.Data.SqlClient
Imports System.Data
Imports System.Collections.Generic
Imports System.Runtime.Serialization.Json
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 ProductsWebService
    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 GetAllProducts() As List(Of Product)
        'Dim reports As New List(Of ModelReport.Report)()
        Dim reports As New List(Of Product)()
        Dim connectionString As String = ConfigurationManager.ConnectionStrings("TestDatabaseConnectionString").ConnectionString
        Using connection As New SqlConnection(connectionString)
            Using command As SqlCommand = connection.CreateCommand
                Dim sql As String = "SELECT [product_id], [product_name], [quantity_per_unit], [unit_price] FROM [TestDatabase].[dbo].[Drinks]"
                connection.Open()

                command.CommandText = sql
                Using reader As SqlDataReader = command.ExecuteReader()
                    While reader.Read()
                        'Dim report As New ModelReport.Report()
                        Dim report As New Product()
                        report.product_id = reader("product_id").ToString()
                        report.product_name = reader("product_name").ToString()
                        report.quantity_per_unit = reader("quantity_per_unit").ToString()
                        report.unit_price = reader("unit_price").ToString()
                        reports.Add(report)
                    End While
                End Using
            End Using
        End Using

        Return reports
    End Function

End Class

Public Class Product
    ' Integer type
    Private privateproduct_id As Integer
    Public Property product_id() As Integer
        Get
            Return privateproduct_id
        End Get
        Set(ByVal value As Integer)
            privateproduct_id = value
        End Set
    End Property
    ' String type
    Private privateproduct_name As String
    Public Property product_name() As String
        Get
            Return privateproduct_name
        End Get
        Set(ByVal value As String)
            privateproduct_name = value
        End Set
    End Property
    ' String type
    Private privatequantity_per_unit As String
    Public Property quantity_per_unit() As String
        Get
            Return privatequantity_per_unit
        End Get
        Set(ByVal value As String)
            privatequantity_per_unit = value
        End Set
    End Property
    ' String type
    Private privateunit_price As String
    Public Property unit_price() As String
        Get
            Return privateunit_price
        End Get
        Set(ByVal value As String)
            privateunit_price = value
        End Set
    End Property
End Class

Open in new window


In the Web.config file of my directory make sure add connection string like this:

  <connectionStrings>
    <add name="TestDatabaseConnectionString" connectionString="Data Source=MYServer;Initial Catalog=TestDatabase;Integrated Security=True"
        providerName="System.Data.SqlClient" />
  </connectionStrings>

Open in new window


So now when I view this WebService in the web browser I get this:

the methods found in my Web Service
The method I am using in this example is the GetAllProducts method.
If I click the GetAllProducts link, then I get an option to invoke it. If I click Invoke then I get this json data array:

json array returns by GetAllProducts method in my Web Service

Step 3          Create ASP.NET page

So now I'm on step 3. I create a page called GetProducts.aspx
I also add the appropriate css and javascript code to this page.

At this point my project directory looks like this:

example 2 project directory
The final code for GetProducts.aspx looks like this:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="GetProducts.aspx.vb" Inherits="ex3.GetProducts" %>

<!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>
<style type="text/css">
.link{
background: #222;
background: -moz-linear-gradient(#252525, #0A0A0A) ;
background: -o-linear-gradient(#252525, #0A0A0A);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#252525), to(#0A0A0A));
background: -webkit-linear-gradient(#252525, #0A0A0A);
-webkit-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
-moz-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
color:#fff;
padding: 8px 10px;
text-decoration: none;
font-weight: normal;
font-size: 18px;
font-family: Arial,Verdana;
word-spacing: 1px;
border-radius: 4px;
-webkit-border-radius: 4px;
-moz-border-radius: 4px;
-o-border-radius: 4px;
-ms-border-radius: 4px;
}
.link:hover{
background:#62ABD8 !important;
background: -moz-linear-gradient(#80BADE, #62ABD8) ;
background: -o-linear-gradient(#80BADE, #62ABD8);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#80BADE), to(#62ABD8));
background: -webkit-linear-gradient(#80BADE, #62ABD8);
-webkit-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
-moz-box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
box-shadow: rgba(0, 0, 0, 0.4) 0px 1px 2px;
}
.link:active{
background:#62ABD8 !important;
background: -moz-linear-gradient(#80BADE, #62ABD8) ;
background: -o-linear-gradient(#80BADE, #62ABD8);
background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#80BADE), to(#62ABD8));
background: -webkit-linear-gradient(#80BADE, #62ABD8);
-webkit-box-shadow: inset rgba(0, 0, 0, 0.4) 0px 1px 2px;
-moz-box-shadow: inset rgba(0, 0, 0, 0.4) 0px 1px 2px;
box-shadow: inset rgba(0, 0, 0, 0.4) 0px 1px 2px;
}
</style>
<style type='text/css'>
.links{
    color: #555;
    padding: 5px;
    cursor: pointer;
}
.hovercard {
    display: none;
    position: absolute;
    width:300px;
padding:3px;
    height: 150px;
    border:1px solid #aaa;
    border-radius: 3px;
    background-color: #fff;
    -webkit-box-shadow:  rgba(0, 0, 0, 0.4) 0px 3px 4px;
-moz-box-shadow:  rgba(0, 0, 0, 0.4) 0px 3px 4px;
box-shadow:  rgba(0, 0, 0, 0.4) 0px 3px 4px;
}
.hovercard:before {
   content: "";
   position: absolute;
   bottom: 100%;
   left: 20px;
   border-bottom: 20px solid black;
   border-bottom-color: inherit; 
   border-left: 20px solid transparent;
   border-right: 20px solid transparent; 
}
.hovercard h3{
    font-family: Verdana, Georgia;
    border-bottom: 1px dashed #ccc;
}
.hovercard a{
    text-decoration: none;
    cursor: pointer;
    border-bottom: 1px dashed #eee;
}
</style>
<script type="text/javascript" src="Scripts/jquery-1.9.1.min.js"></script>
<script type='text/javascript'>
    $(document).ready(function (e) {
        $('span[rel="hovercard"]').hover(
        function (e) {
            position = $(this).position();
            x = $(this).data('url');

            //$.getJSON('hover_data_products.json', function (data) {
            $.getJSON('ProductsWebService.asmx/GetAllProducts', function (data) {
                $('.hovercard').html('</h3>Product ID : ' + eval('data.' + x + '.product_id') + '<br/></h3>Product Name : ' + eval('data.' + x + '.product_name') + '<br/></h3>Quantity Per Unit : ' + eval('data.' + x + '.quantity_per_unit') + '<br/></h3>Unit Prie : ' + eval('data.' + x + '.unit_price'))
            })
            $('.hovercard').show().css('top', position.bottom).css('left', position.left);
            //Mouse In code
        },
        function (e) {
            $('.hovercard').hide();
            //Mouse Out code
            $('hovercard').html('');
        });
    });
</script>
</head>
<body>
   <form id="form1" runat="server">
<div style="width:100%;text-align:center;margin:0 auto;">
    <div><center><h1>Time to Hack</h1>
        <h3><a href="" class="link">Back to Tutorial</a></h3></center>
    </div>
    <hr>
    <br/>
<div>Hover These Texts</div><br>
<span rel='hovercard' data-url='TeamID_01' class="links">Chai</span>|<span rel='hovercard' data-url='TeamID_02' class="links">Chang</span>
</div>
<br>
<br>
 
<div class="hovercard"></div>
  
<style type="text/css">
#pankaj{
    display: block;
    width:728;
    height:90;
    line-height: 50px;
    font-weight: 25px;
    text-align: center;
    margin: 0 auto;
    border:1px solid #ccc;
    margin-top: 10px;
    -webkit-transition: 2000ms;
}
#pankaj:hover{
    transform: rotateY(180deg);
-webkit-transform: rotateY(180deg);
-webkit-transition: 2000ms;
-moz-transform: rotateY(180deg);
-moz-transition: 2000ms;
-ms-transform: rotateY(180deg);
-ms-transition: 2000ms;
-o-transform: rotateY(180deg);
-o-transition: 2000ms;
 
}
    .style1
    {
        width: 60%;
    }
    .style2
    {
        width: 163px;
        text-align: center;
    }
    .style3
    {
        width: 437px;
    }
</style> 

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

Open in new window



The final code for GetProducts.aspx.vb looks like this:

Public Class GetProducts
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

End Class

Open in new window


Step 4      Run Application

So when I run GetProducts.aspx , I get this:

when I run example 2
When I mouse over either the Chai or Chang words I should see the data just like in example 1 above but it's not showing up in this example.

I'm sure the problem is in how i'm fetching the json data from the web service.
I think the error is in the Javascript in the part where i'm using the $.getJSON function.

Anyone know how I should be calling my Web Service array?
0
Comment
Question by:maqskywalker
1 Comment
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39241062
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Introduction If you're like most people, you have occasionally made a typographical error when you're entering information into an online form.  And to your consternation, the browser remembers the error, and offers to autocomplete your future entr…
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…

759 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