'Data in ajax json not defined
this is my data looks like in json in harcoded way. But i want to retreive the data from database. so it can be display in html like how json display it.
menu_data = {
"name": "Abu",
"menus": [
{
"menu_id": 1,
"name": "Food",
"icon": "fa-hdd-o",
"col": 4,
"site": Ind,
"subs": [
[
{
"name": "Cake",
"path": "",
"url": "",
"tabs": "",
"param": ""
},
{
"name": "Cheese Cake",
"path": "",
"url": "",
"tabs": "",
"param": ""
},
{
"name": "Choc Cake",
"path": "",
"url": "",
"tabs": "",
"param": ""
},
],
]
},
],
"gid": "00001",
"message": null
};
But i want to get all this data from database which means i need to get the data from web service. This is my code in webservice c#.
public class wsResult
{
public string message;
}
public class wsMenu
{
public string menu_id;
public string name;
public string icon;
public string site;
public string col;
public List<string> subs = new List<string>();
}
public class wsHome : wsResult
{
public string name;
public List<wsMenu> menus;
public string gid;
}
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = false)]
public List<wsMenu> GetModName()
{
List<wsMenu> food = new List<wsMenu>();
{
using (DbConnection conn = SingLibrary.CreateConnection("foodddb_dev"))
{
conn.Open();
DbCommand cmd = SingLibrary.CreateCommand(conn);
cmd.CommandText = String.Format(
@"select name, menu_id, site from
food_menu ");
DbDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
wsMenu op = new wsMenu();
op.name = dr["name"].ToString();
op.menu_id = dr["menu_id"].ToString();
op.site = dr["site"].ToString();
food.Add(op);
}
dr.Close();
}
}
return food ;
}
and this is my ajax script...
function setMenu() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ws.asmx/GetModName",
data: menu_data,
dataType: "json",
async: true,
success: function (menu_data) {
menu_data = menu_data.d;
console.log("this is menu data length " + menu_data.length);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
});
I getting this error " menu_data is null " and "menu data is not defined"
Solution 1:[1]
try to remove data: and content type from ajax
$.ajax({
type: "POST",
url: "ws.asmx/GetModName",
dataType: "json",
success: function (menu_data) {
menu_data = menu_data.d;
console.log("this is menu data length " + menu_data.length);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR, textStatus, errorThrown);
}
});
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |
