Solved

json data formats

Posted on 2013-06-15
1
334 Views
Last Modified: 2013-06-17
Hi experts,

I read that the $.getJSON function is a shorthand version of the $.ajax function.

So I'm trying to learn to write each of these 2 functions to call some json data.

So I created a Web Service called EmployeesWebService.asmx
This web service uses the Employees table of the Northwind sql server database.

Here 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

    ' This method returns a Json type.
    <WebMethod()> _
    <ScriptMethod(UseHttpGet:=False, ResponseFormat:=ResponseFormat.Json)> _
    Public Function GetEmployees() As List(Of Employee)

        Dim info As New List(Of Employee)()

        Dim mycon As SqlConnection
        mycon = New SqlConnection("Data Source=MYServer\SQLEXPRESS;Initial Catalog=Northwind;Integrated Security=True")
        mycon.Open()
        Dim query As String = "SELECT [EmployeeID],[LastName],[FirstName]  FROM [Northwind].[dbo].[Employees]"
        Dim cmd As New SqlCommand(query, mycon)
        'cmd.Parameters.AddWithValue("@id", id)

        Dim reader As SqlDataReader
        reader = cmd.ExecuteReader()
        While reader.Read()
            Dim b As New Employee()
            b.EmployeeID = reader.GetInt32(0)
            b.LastName = reader.GetString(1)
            b.FirstName = reader.GetString(2)
            info.Add(b)
        End While
        reader.Close()
        ' close the connection
        mycon.Close()

        Return info
    End Function

End Class

' Employee class
Public Class Employee
    ' Integer type
    Public Property EmployeeID() As Integer
        Get
            Return m_EmployeeID
        End Get
        Set(value As Integer)
            m_EmployeeID = value
        End Set
    End Property
    Private m_EmployeeID As String
    ' String type
    Public Property LastName() As String
        Get
            Return m_LastName
        End Get
        Set(value As String)
            m_LastName = value
        End Set
    End Property
    Private m_LastName As String
    ' String type
    Public Property FirstName() As String
        Get
            Return m_FirstName
        End Get
        Set(value As String)
            m_FirstName = value
        End Set
    End Property
    Private m_FirstName As String
End Class

Open in new window


When I run the service and click on the GetEmployees method  I get this:

GetEmployees method

Fetching json with $.Ajax function

So I created a asp page called EmployeesAjaxJson3WS.aspx

This is the code for it:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EmployeesAjaxJson3WS.aspx.vb" Inherits="JSONExamples.EmployeesAjaxJson3WS" %>

<!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>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/GetEmployees",
                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><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:

using the $.ajax method
So by using the $.ajax method the json data from the web service is fetched correctly.



Fetching json with $.getJSON function

So now I'm trying to fetch the same json data from the same web service but this time I want to use the $.getJSON function.

So I created a page called EmployeesGetJson3WS.aspx

This is the code for it:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="EmployeesGetJson3WS.aspx.vb" Inherits="JSONExamples.EmployeesGetJson3WS" %>

<!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>example fetching JSON data using getJSON 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 () {
            $.getJSON("EmployeesWebService.asmx/GetEmployees", function (data) {
                $.each(data, function () {
                    $.each(this, function (key, value) {
                        $("#teamemployees").append(
                            "EmployeeID: " + value.EmployeeID + "<br>" +
                            "LastName: " + value.LastName + "<br>" +
                            "FirstName: " + value.FirstName + "<br><br>"
                        );
                    });
                });
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">

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

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

Open in new window


But when I run this page I just get a blank page.

Am i missing something? Or did I write something wrong in the $.getJSON function?
Can someone help?
0
Comment
Question by:maqskywalker
1 Comment
 
LVL 82

Accepted Solution

by:
leakim971 earned 500 total points
ID: 39250070
Using $.ajax instead $.getJSON let you add lot of parameters
Check the docs to see the difference :
http://api.jquery.com/jQuery.ajax/
http://api.jquery.com/jQuery.getJSON/

Especially : contentType and error.
You can use $.ajaxSetup to set this parameter for $.getJSON BUT this will become the setup for every ajax call using shortcut jquery ajax method (not $.ajax : $.post, $.getJSON, $.get, $.load)

Currently you get an error on the client side but don't handling error so you can't notice it.
Check this usefull article :
http://encosia.com/using-jquery-to-consume-aspnet-json-web-services/

The parts : Additional security when calling JSON serialized services, How to make jQuery jump through these hoops
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
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 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)
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…

708 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

15 Experts available now in Live!

Get 1:1 Help Now