Hi!
I have a webservice that return JSON data but when I consume through ajax JQUERY it is returning error:
Error: TypeError: r is null
Source File: http://localhost:23967/WebServiceConsume.aspx
Line: 22 When I run webservice directly in browser as: http://192.168.200.35/WebSite8/WebService.asmx/GetCountries: Result is : <string>[{"CID":1,"CountryName":"India"},{"CID":2,"CountryName":"Pakistan"},{"CID":3,"CountryName":"Afganistan"},{"CID":4,"CountryName":"USA"},{"CID":5,"CountryName":"America"}]</string>
Here is code:
Webservice Code: using System;
[WebMethod(CacheDuration = 0, Description = "Country Name")]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetCountries()
{
try
{
DataTable dt = new DataTable("CountryTable");
string query = "SELECT * FROM Country";
m_Connection.OpenDB("IGDB");
OdbcCommand m_Command = new OdbcCommand(query, m_Connection.oCon);
m_Command.CommandType = CommandType.Text;
m_Command.Connection = m_Connection.oCon;
OdbcDataAdapter m_DataAdapter = new OdbcDataAdapter(m_Command);
m_DataAdapter.Fill(dt);
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
catch (Exception)
{
throw;
}
}
on my aspx page I am consuming this way:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="WebServiceConsume.aspx.cs" Inherits="WebServiceConsume" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="js/jquery.min.js"></script>
<script src="script/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
url: 'http://192.168.200.35/WebSite8/WebService.asmx/GetCountries',
data: "{}",
type: "POST",
cache: false,
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (data) {
alert(data.d);
},
error: function (data) {
alert("Error"); //do something if there is an error
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<div id="response"></div>
</div>
</form>
</body>
</html>