display data from database in angularjs and json - javascript

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.

Related

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();
}
}

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" }

Why is my C# method not being called from AJAX?

I am trying to call the following C# method:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string getJSONdata()
{
string jsonString = "";
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT TOP 10 * FROM DRAW ORDER BY DrawID DESC;", con))
{
using (SqlDataReader reader = cmd.ExecuteReader())
{
List<Dot> _Dot = new List<Dot>();
while (reader.Read())
{
Dot dot = new Dot();
dot.x = (int.Parse(reader["xCoord"].ToString()));
dot.y = (int.Parse(reader["yCoord"].ToString()));
if (reader["DrawID"] != DBNull.Value)
dot.i = (int.Parse(reader["DrawID"].ToString()));
_Dot.Add(dot);
}
JavaScriptSerializer jss = new JavaScriptSerializer();
jsonString = jss.Serialize(_Dot);
}
}
}
System.Diagnostics.Debug.WriteLine(" JSON: " + jsonString);
return jsonString;
}
Here is my JavaScript code:
$.ajax({
url: 'Default.aspx/getJSONdata',
data: '{ }',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response.d);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
First, I am getting the ajax error. No idea why it's not called.
Second, I am still not sure I am returning the correct JSON data I want, whether in the correct format or not. Thanks for your help.
Edit. It is returning a JSON string correctly.
Note: the connectionString works in another function, so that's not it.
Download and install Fidder4.
This will allow you to see the traffic between your page and your server. You can see the actual call URL and then paste it into a browser to see what it returns. This will give you a tool to solve this type of problem going forward.

Why can't I use my JSON data?

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);
}
});

500 internal server error ajax/javascript

I know there is some posts on this but they did not help me.
My program run's and when I click on a button to fire a javascript nothing happens, or no response. In chrome debugger under network tab I see in red
http://wms-wsdl.company.net/mobile.asmx/ContactGet?searchField=test&office=97&person=119&user=531&organization=14
when I click on that link it shows a red circle with 500 internal server error.
If I click on the response I see:
{"Message":"Invalid JSON primitive: test.","StackTrace":" at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializePrimitiveObject()\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal(Int32 depth)\r\n at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit)\r\n at System.Web.Script.Services.RestHandler.GetRawParamsFromGetRequest(HttpContext context, JavaScriptSerializer serializer, WebServiceMethodData methodData)\r\n at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}
Now I have no Idea what that means.
When I double click in that lick It shows me all my data that is supposed to be inserted into a list view (data is xml) e.g. <string xmlns="http://company.net/">
[ { "Name": "Myar", "Surname": "Tester", "Mobile": "080000000", "Email": "" ......}, etc
My javascript function is as follows:
function initContactView()
{
alert("ContactView start test")
var txtSearch = $("#searchTextField").val();
$.ajax({
type: "GET",
dataType:"json",
contentType: "application/json; charset=utf-8",
crossDomain: true,
url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
success:successContact,
failure: function (msg) {
console.log(msg);
alert(msg)
}
});
alert("ContactView End Test");
}
function successContact(data) {
alert("Success Start Test");
window.location = "#contactsview";
$("#lstView_contacts").kendoMobileListView({
dataSource: JSON.parse(data.d),
template: $("#lstView_contact_Template").html(),
endlessScroll: true,
scrollThreshold: 8
});
alert("Success Start Test");
}
searchTextField comes from my HTML textbox.
What I seem to find odd is that it gets the data it should, I have verified that in the xml but still gives an error.
My webservice that I am using is a json webservice.
It alerts both alerts but I think it goes into failure.
The response i get in debugger is:
<string xmlns="http://company.net/">[
{
"Name": "Myar",
"Surname": "Tester",
"Mobile": "080000000",
"Email": "test#test.com"
}]</string
How my webservice looks:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function ContactGet(ByVal searchField As String, ByVal office As String, ByVal person As String, ByVal user As String, ByVal organization As String) As String
Dim objSearch As New ArrayList
Dim objSearching As New Search
Dim intResult As Integer
Try
'Test String
intResult = objSearching.SearchByKeyword(searchField, person, office, organization, user, company.ETMyProperty.Search.enmSearchType.enmContact, objSearch)
Dim objContact As New Person
Dim dt As New DataTable("Contacts")
Dim col_Name As New DataColumn("Name", GetType(String))
dt.Columns.Add(col_Name)
Dim col_Mobile As New DataColumn("Surname", GetType(String))
dt.Columns.Add(col_Mobile)
Dim col_Office As New DataColumn("Mobile", GetType(String))
dt.Columns.Add(col_Office)
Dim col_Category As New DataColumn("Email", GetType(String))
dt.Columns.Add(col_Category)
Dim dr As DataRow
For i = 0 To objSearch.Count - 1
dr = dt.NewRow()
dr("Name") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return2
dr("Surname") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return3
dr("Mobile") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return6
dr("Email") = DirectCast(objSearch(i), company.ETMyProperty.Search).Return7
dt.Rows.Add(dr)
Next
Dim serializer As New JavaScriptSerializer()
Dim rows As New List(Of Dictionary(Of String, Object))()
Dim row As Dictionary(Of String, Object) = Nothing
'serialize dt row to json output
For Each drow 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
Dim str_json = JsonConvert.SerializeObject(dt, Formatting.Indented)
Return str_json
Catch ex As Exception
Return Nothing
End Try
End Function
I have been on this for a few days now and I cant seem to get any solution.
Any help?
Refering to jQuery doc, you should use error: function() {...}, and not failure.
The value for the key success should be a function, and not a variable. Something like success: successContact(),
For debugging in some usefull way, you NEED to know, if your ajaxcallback calls success or error. If it does not call success, it is probably because the answer has no application/json content-type header, or your json is wrong.
Cause you are seding a GET request, you have to remove or define the contentType as:
application/x-www-form-urlencoded; charset=UTF-8
function initContactView()
{
alert("ContactView start test")
var txtSearch = $("#searchTextField").val();
$.ajax({
type: "GET",
dataType:"json",
crossDomain: true,
url: "http://dsf-wsdl.company.net/mobile.asmx/ContactGet",
data: "searchField="+txtSearch+"&office="+localStorage.getItem("office")+"&person="+localStorage.getItem("person")+"&user="+localStorage.getItem("user")+"&organization="+localStorage.getItem("organization"),
success:function (data) {successContact(data);},
failure: function (msg) {
console.log(msg);
alert(msg)
}
});
alert("ContactView End Test");
}
Check too if the error is when the Request Begin on the ASMX or the error is on the ASMX Response.
Check this for Details Get Request:
Do I need a content type for http get requests?
Also configure your webservice to return JSON. The response isn't json.
So, the dataType now is not correct. To retrun ONLY json change your WebMethod.
[WebMethod]
[ScriptMethod(UseHttpGet=true ,ResponseFormat = ResponseFormat.Json)]
public void HelloWorld()
{
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write("Hello World");
//return "Hello World";
}
Important: if you are using webmethods you don't need to parse the datatable to json, webservice will do it for you.
So change this to:
<WebMethod()> _
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=True)> _
Public Function ContactGet(ByVal Parameters....) As DataTable
After all, this is an example that works with the .net serialization
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;
using System.Collections;
using System.Linq;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<Dictionary<string, object>> HelloWorld()
{
DataTable TestTable = new DataTable();
TestTable.Columns.Add("Name");
TestTable.Columns.Add("Id");
DataRow Row = TestTable.NewRow();
Row["Name"] = "James";
Row["Id"] = 0;
TestTable.Rows.Add(Row);
return RowsToDictionary(TestTable);
}
private static List<Dictionary<string, object>> RowsToDictionary(DataTable table)
{
List<Dictionary<string, object>> objs =
new List<Dictionary<string, object>>();
foreach (DataRow dr in table.Rows)
{
Dictionary<string, object> drow = new Dictionary<string, object>();
for (int i = 0; i < table.Columns.Count; i++)
{
drow.Add(table.Columns[i].ColumnName, dr[i]);
}
objs.Add(drow);
}
return objs;
}
}
Please, check another serializers like http://james.newtonking.com/json. Perhaps you can use better a ASHX handler than a ASMX for returning JSON.

Categories

Resources