Why can't I use my JSON data? - javascript

I am trying to read some JSON data from an AJAX function. Here is the AJAX I am using:
$.ajax({
type: 'POST',
cache: false,
url: 'Default.aspx/GetCoords',
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
var text = JSON.stringify(data);
$("#jsonData").html(text);
alert(text);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I also have use JSON.parse in place of stringify, and objects return undefined or not at all. This comes from a C# function which looks like this:
[WebMethod]
[ScriptMethod]
public static string GetCoords()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new 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);
}
System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
return serializer.Serialize(rows);
}
}
}
It is returning JSON data: Here is what it looks like on the Debugger Console and when I call the function in a paragraph tag:
[{"DrawID":925,"xCoord":466,"yCoord":201},{"DrawID":924,"xCoord":385,"yCoord":318},{"DrawID":923,"xCoord":768,"yCoord":159},{"DrawID":922,"xCoord":543,"yCoord":214},{"DrawID":921,"xCoord":329,"yCoord":172}]
However, when I send it to the paragraph tag in JQuery or call it in an HTML paragraph, here is what it looks like:
{"d":"[{\"DrawID\":925,\"xCoord\":466,\"yCoord\":201},{\"DrawID\":924,\"xCoord\":385,\"yCoord\":318},{\"DrawID\":923,\"xCoord\":768,\"yCoord\":159},{\"DrawID\":922,\"xCoord\":543,\"yCoord\":214},{\"DrawID\":921,\"xCoord\":329,\"yCoord\":172}]"}
I have two questions:
(1) Why am I not able to use this data to insert the xCoords and yCoords into a canvas? I have tried many formats: (data.d[0].xCoord, d[0].xCoord, text.d[0].xCoord, text[0].xCoord, and so on).
(2) Is the second format above going to be a problem in trying to extract that data for painting on the canvas (it's the backslashes that I am wondering about)?
Thanks.

In your success function, you do not stringify or json.Parse the 'data' variable, but rather the data.d variable. 'd' is the member of the json return that you need to parse.
So, change, var text = JSON.stringify(data); to var text = JSON.stringify(data.d); and you should be golden.

You need to use parseJSON, as such:
myThing = {"d":"[{\"DrawID\":925,\"xCoord\":466,\"yCoord\":201},{\"DrawID\":924,\"xCoord\":385,\"yCoord\":318},{\"DrawID\":923,\"xCoord\":768,\"yCoord\":159},{\"DrawID\":922,\"xCoord\":543,\"yCoord\":214},{\"DrawID\":921,\"xCoord\":329,\"yCoord\":172}]"};
myJSON = $.parseJSON(myThing.d);
alert (myJSON[0].DrawID); //etc

I had to return rows in my C# code as #lujcon said:
[WebMethod]
[ScriptMethod]
public static List<Dictionary<string, object>> GetCoords()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new 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);
}
System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
return rows;
}
}
}
Then I had to change my var text = JSON.stringify(data); to var text = JSON.stringify(data.d); as #JustinRusso said. Works now. Thanks, everyone.

[WebMethod]
[ScriptMethod]
public static Dictionary<string, object>[] GetCoords()
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
JavaScriptSerializer serializer = new 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);
}
System.Diagnostics.Debug.WriteLine(serializer.Serialize(rows));
return rows.ToArray();
}
}
}
Java script:
$.ajax({
type: 'POST',
cache: false,
url: 'Default.aspx/GetCoords',
data: "{}",
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
$.each(data, function(index, value) {
var x = value.xCoord;
/// do something with it ;)
});
var text = JSON.stringify(data);
$("#jsonData").html(text);
alert(text);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});

Related

Ajax returning datatable always going in error part in asp.net

I return list of values in a datatable and that I want to fill in success part of ajax function in dropdownlist. Till return dt I get all the values properly but after that it goes in error part. Below is what I tried.
Ajax function
function getMZONEWithState(evt) {
var ddlState = $('#ContentPlaceHolder1_ddlState').val();
var ddlMaintenanceZone = $("#ddlMaintenanceZone");
ddlMaintenanceZone.empty().append('<option selected="selected" value="0" disabled = "disabled">State Loading...</option>');
$.ajax({
type: "POST",
url: "Dashboard.aspx/GetMaintZone",
data: JSON.stringify({ ddlState: ddlState }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
},
error: function (response) {
alert('Something went wrong..!!');
}
});
}
And in code behind:-
[WebMethod]
public static DataTable GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return dt;
}
catch (Exception)
{
throw;
}
}
Why it always goes in error part I don't understand ?? Please suggest If I am going wrong anywhere.
You can't return DataTable directly from your [WebMethod] like this. You need to convert your DataTable to JSON before sending to cleint.
Change your server side code like following.
[WebMethod]
public static string GetMaintZone(string ddlState)
{
DataTable dt = new DataTable();
try
{
CommonDB ObjCommon = new CommonDB();
dt = ObjCommon.GetMZONE(ddlState);
return DataTableToJSON(dt);
}
catch (Exception)
{
throw;
}
}
public static string DataTableToJSON(DataTable table)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
List<Dictionary<string, object>> parentRow = new List<Dictionary<string, object>>();
Dictionary<string, object> childRow;
foreach (DataRow row in table.Rows)
{
childRow = new Dictionary<string, object>();
foreach (DataColumn col in table.Columns)
{
childRow.Add(col.ColumnName, row[col]);
}
parentRow.Add(childRow);
}
return jsSerializer.Serialize(parentRow);
}
}

ASP.NET ajax call using Jquery adds to list

I have a simple UI where I am trying to populate the select dropdown using data from database. I am doing this by a AJAX call to fetch the data.
The C# web method looks like
private static List<List<string>> componentTypeDropDown = new List<List<String>>();
private void loadDropDownList()
{
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}
[WebMethod]
public static ArrayList getComponentType()
{
ArrayList compType = new ArrayList();
for (int i=0;i<componentTypeDropDown.Count();i++)
{
compType.Add(new { label = componentTypeDropDown[i][0], value = componentTypeDropDown[i][1] });
}
return compType;
}
The AJAX call looks like
$.ajax({
type: "POST",
url: "salesQuote.aspx/getComponentType",
data: "",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
console.log("karan");
},
error: function () {
alert("Failed to load names");
}
});
Every time I refresh or even restart the server the value of msg in success callback has previous values as well. For example lets say my database has value 1,2. First time I call ajax msg is 1,2 if i refresh the value is 1,2,1,2 and so on. Even if I close the server and start again the value would be 1,2,1,2,1,2
Your ComponentTypeDropdown is a static, so every time you call 'LoadDropdownList' this list will add new items, whitout removing the old ones.
I would suggest that you add following line in the loadDropDownList method:
private void loadDropDownList()
{
componentTypeDropdown.RemoveAll();
OleDbConnection conn = new OleDbConnection(connectionString);
OleDbCommand cmd = new OleDbCommand("SELECT FieldName,FieldLabel FROM dropDownFields", conn);
conn.Open();
OleDbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
List<String> temp = new List<string>();
temp.Add((string)dr.GetValue(0));
temp.Add((string)dr.GetValue(1));
componentTypeDropDown.Add(temp);
conn.Close();
}
}

display data from database in angularjs and json

I am trying to display data from database in angularjs using webservice
But geting Error[object Object] while retriving data
My web method is:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)> _
Public Function GetData() As String
Dim strCon As SqlConnection = New SqlConnection("Data Source=PC12\SQL2;Initial Catalog=TestData;User ID=abc;Password=xxxx; timeout=0;")
Dim dt As DataTable = New DataTable
Dim da As SqlDataAdapter
Dim cmd As SqlCommand = New SqlCommand("select * from user", strCon)
strCon.Open()
da = New SqlDataAdapter(cmd)
da.Fill(dt)
Dim serializer As New System.Web.Script.Serialization.JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object)
For Each dr As DataRow In dt.Rows
row = New Dictionary(Of String, Object)()
For Each col As DataColumn In dt.Columns
row.Add(col.ColumnName, dr(col))
Next
rows.Add(row)
Next
Return serializer.Serialize(rows)
End Function
My javascript to call webservice:-
$(document).ready(function () {
$.ajax({
type: 'POST',
url: 'WebService1.asmx/GetData',
data: '{}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (data) {
alert("Result: " + data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown + XMLHttpRequest + textStatus);
}
});
});
Got the solution
I haven't added attribute in my web service.
Only Web services with a attribute on the class definition can be called from script.
After adding got the data.

AJAX call a function with a parameter

The following gives me a internal server error.
var jsonStateData;
$.ajax({
type: "POST",
url: "functions.aspx/StateSalesDataString",
data: '{' + 'AL' + '}',
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
jsonStateData = $.parseJSON(data.d);
}
}).done(function () {
console.log(jsonStateData);
})
This is the function that it is calling
//Returns stores sales datatable
[WebMethod]
public static string StateSalesDataString(string whichState)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Dashboard_VWConnectionStringTest"].ConnectionString);
conn.Open();
string storeSalesQuery = "SELECT StoreSalesTbl.StoreNumb, Lat, Lng, TodayTotalSales, TodayTotalOrders, TodayTotalWebSales, TodayTotalCallSales, TodayTotalIFSales, TodayTotalStoreSales, TodayTotalWebOrders, TodayTotalCallOrders, TodayTotalIFOrders, TodayTotalStoreOrders " +
"From StoreSalesTbl INNER JOIN StoreAddreTbl " +
"ON StoreSalesTbl.StoreID = StoreAddreTbl.StoreID " +
"Where DatetimeTo IN (SELECT max(DatetimeTo) FROM StoreSalesTbl) " +
"AND StoreAddreTbl.State = #stateName";
SqlCommand storeComm = new SqlCommand(storeSalesQuery, conn);
storeComm.Parameters.AddWithValue("#stateName", whichState);
storeComm.CommandType = CommandType.Text;
// Create a DataAdapter to run the command and fill the DataTable
SqlDataAdapter dataAdpt = new SqlDataAdapter();
dataAdpt.SelectCommand = storeComm;
DataTable storeDataTbl = new DataTable();
dataAdpt.Fill(storeDataTbl);
conn.Close();
//convert the datatable to string
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 storeDataTbl.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in storeDataTbl.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
UPDATE
Thank you guys for answering! I think my problem might also be in my c# function. Am I doing anything wrong with the query statement #stateName part?
Because when I changed the query's last line to just
AND StoreAddreTbl.State = 'AL'"
It worked. But when I pass the string whichState in there, it didn't proceed.
Your JSON is invalid. You have it looking like this:
{'AL'}
It should be looking similar to this:
{ "whichState": "AL" }
The proper way to do this in JavaScript:
var myData = {};
myData.whichState = 'AL';
var jsonStateData;
$.ajax({
type: "POST",
url: "functions.aspx/StateSalesDataString",
data: JSON.stringify(myData),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
jsonStateData = $.parseJSON(data.d);
}
}).done(function () {
console.log(jsonStateData);
})
Notice on the data parameter, I'm using JSON.stringify. The JavaScript JSON.stringify function will automatically create your JSON string for you.
When sending the data, give it the key you expect to assign it to. For example, you should be able to do:
data: { "whichState" : "AL" }

MVC 3 .NET Fill fields dynamically

I have a field for a ZIP Code.
I want that, when the person fills this field with a zip code and click in another field, triggers a event (onBlur).
This Event will execute a select in database and get the address and fill the other fields with this information.
I read that is not a good idea execute a Controller Method from the View.
So, how can I develop this?
My zip code field:
<div class="editor-field">
#Html.Label("ZIP CODE")
#Html.Editor("zipCodeClient")
</div>
Thanks!
If you have access to jQuery I would use it's ajax function to call a wcf web service that returns the relevant address information in a JSON format. Otherwise, you could create your own XHR request and parse the response.
$('#zipCodeClient').blur(function() {
var zipCode = $(this).val();
if(zipCode.length >= 5 && zipCode.length <= 10) {
$.ajax({
type: 'GET',
data: { ZipCode: zipCode },
url: 'something/ZipCodeToAddressService',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
success: function(data) {
var responseObject = jQuery.parseJSON(data);
$('#cityTextBox').val(responseObject.City);
$('#stateTextBox').val(responseObject.State);
}
});
}
else {
// zip code not valid
}
});
In WCF:
[ServiceContract()]
public interface IAddressServices
{
[OperationContract()]
[WebGet(ResponseFormat = WebMessageFormat.Json)]
string ZipCodeToAddressService(string ZipCode);
}
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class AddressServices : IAddressServices
{
public string ZipCodeToAddressService(string ZipCode)
{
using (SqlConnection sqlConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["DB"].ConnectionString))
{
using (SqlCommand sqlCmd = new SqlCommand("ZipCodeToAddressStoredProc", sqlConnection))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.Add("#Zip", SqlDbType.NVarChar).Value = ZipCode;
sqlConnection.Open();
SqlDataReader sDR = sqlCmd.ExecuteReader(CommandBehavior.CloseConnection);
DataTable tbl = new DataTable();
tbl.Load(sDR);
sDR.Close();
var citystateData = from DataRow Row in tbl.AsEnumerable()
select new
{
City = Row.Field<string>("City"),
State = Row.Field<string>("State")
};
JavaScriptSerializer js = new JavaScriptSerializer();
StringBuilder sb = new StringBuilder();
js.Serialize(cityStateData, sb);
string rtrnCityStateData = sb.ToString();
return rtrnCityStateData;
}
}
}
}

Categories

Resources