Simplest Tutorial for AJAX, JQUERY, WebService Call returning JSON

This is a tutorial for calling a WebService from an ASMX page in it’sĀ simplestĀ form.

Code Behind

[codesyntax lang=”vbnet”]

Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols

‘ To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:=”http://tempuri.org/”)> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class MyWebService
Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function ReturnJSONData() As Person
Dim guy As New Person
guy.Name1 = “MeNameASMX”
guy.Age = 18
Return guy
End Function

End Class

Public Class Person
Private _name As String
Public Property Name1() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _age As Int32
Public Property Age() As Int32
Get
Return _age
End Get
Set(ByVal value As Int32)
_age = value
End Set
End Property
End Class

[/codesyntax]

 

ASPX Page that will be calling the ASMX WebService

[codesyntax lang=”html4strict”]

<%@ Page Language=”VB” AutoEventWireup=”false” CodeFile=”WebService_ASMX_JQuery.aspx.vb” Inherits=”WebService_ASMX” %>

<!DOCTYPE html>

<html xmlns=”http://www.w3.org/1999/xhtml”>
<head runat=”server”>
<title></title>
</head>
<body>
<script src=”//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js”></script>

<form id=”form1″ runat=”server”>
<a href=”#” id=”Result”>Click for Call</a>
</form>

<script>
$(document).ready(function () {
$(“#Result”).click(function () {
$.ajax({
type: “POST”,
url: “MyWebService.asmx/ReturnJSONData”,
data: “{}”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function (msg) {
alert(msg.d.Name1 + ‘:’ + msg.d.Age);
}
});
});
});
</script>

</body>
</html>

[/codesyntax]