I'm trying to get a serialized json list via ajax and create dynamic table in a html jquery mobile page. the list comes from a sql database in code behind. I just don't know if I'm returing the json object right, and how to access it from the ajax success function.
My goal is to create dynamically a table of all the members in the html.
I created a Member class:
public class Member
{
public Member()
{
//
// TODO: Add constructor logic here
//
}
public String fName { set; get; }
public String lName { set; get; }
}
This is my function to return the member list in code behind: (written in a class that connects with the sql)
public List<Member> return_member_list()
{
List<Member> member_list = new List<Member>();
String fName;
String lName;
SqlConnection user_con = connect("ActConString");
SqlCommand user_command = create_command(user_con, "select m_first_name, m_last_name from member");
SqlDataReader rdr = user_command.ExecuteReader();
while (rdr.Read())
{
Member m1 = new Member();
fName = Convert.ToString(rdr["m_first_name"]);
lName = rdr["m_last_name"].ToString();
m1.fName = fName;
m1.lName = lName;
member_list.Add(m1);
}
rdr.Close();
user_con.Close();
return member_list;
}
then I use an aspx page web method to return the list serialized:
[WebMethod]
public static String return_member_list()
{
dbservices db1 = new dbservices();
List<Member> member_list = db1.return_member_list();
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(member_list);
return json;
}
and the ajax:
$(document).ready(function () {
$.ajax({
type: "POST",
url: "getdata.aspx/return_member_list",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
//this is where I need help
},
error: function (res, msg, code) {
// log the error to the console
alert("The following error occured: " + msg + " " + code);
} //error
});
});
I'd appriciate help with creating the table dynamically as well
Sumit Kesarwani
01-Sep-2014You need to do the success function as below
success: function (res) {
var parsedData = JSON.parse(res.d);
var tableStr = "<table>";
$.each(parsedData, function(){
tableStr +="<tr><td>"+this.fName+"</td><td>"+this.lName+"</td></tr>";
});
tableStr += "</table>";
$('#tableDiv').html(tableStr);
}
Assumes that you have a div with the id tableDiv