i am trying to populate html table from database c# and jquery AJax.But while i run it. it gives sometime success and some time Undefined And Sometime Blank Alert Box by while i pass same parameter every time.And When It Success It Bind Table But this table couln't hols on page it shows but disappear at once.
Here Is My Code:
C# Code
[WebMethod]
public static Report[] databind(string srh)
{
List<Report> list1 = new List<Report>();
try
{
DataTable dt = SQLDatabaseManager.ExecuteDataTable("select *,convert(nvarchar,IssueDate,106) as Idate,convert(nvarchar,ValidDate,106) as Vdate,convert(nvarchar,NextAuditDate,106) as Ndate from [Staun_Icrtms].[tbl_Clients] where Org_name like '%" + srh + "%' order by Org_name desc ");
if (dt != null && dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
Report data1 = new Report();
data1.orgName = dr["org_name"].ToString();
list1.Add(data1);
}
}
return list1.ToArray();
}
catch (Exception ex)
{
return list1.ToArray();
}
}
}
Jquery Ajax
function DataBind() {
debugger;
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: "ClientReport.aspx/databind",
data: "{srh:" + JSON.stringify($('#txtName').val()) + "}",
dataType: 'json',
success: function (data)
{
if (data.d.length > 0) {
alert('Success')
for (var i = 0; i < data.d.length; i++) {
$('#tblClient').append('<tr><td>' + data.d[i].orgName + '<td><tr/>');
}
}
},
error: function (xhr)
{
alert(xhr.responseText);
}
})
}
Related
On my web page I used jquery and ajax to call a C# function to fill Dropdown list with respect to another
Dropdown Branch is filled as per the selection of zone and Employee with the selection of branch.It works perfect But the button Click is not working after this.Someone please tell me why this button click is not working??
[Button click works when no drop down selection is made]
my Code look Like this:
Jquery
<script src="jquery-1.11.1.min.js"></script>
<script type="text/javascript">
$(function () {
$('#<%= ddZone.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/BranchFill",
data: "{'Zone':'" + $("[id*=ddZone] option:selected").text() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlBranch = $("[id*=ddBranch]");
ddlBranch.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlBranch.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
$('#<%= ddBranch.ClientID %>').change(function () {
$.ajax({
type: "POST",
url: "Reports.aspx/EmployeeFill",
data: "{'Branch':'" + $(this).val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
function OnSuccess(response) {
var ddlEmployee = $("[id*=ddEmployee]");
ddlEmployee.empty().append('<option selected="selected" value="0">--Select--</option>');
$.each(response.d, function () {
ddlEmployee.append($("<option></option>").val(this['Value']).html(this['Text']));
});
if (response.d == "false") {
alert("Not found");
}
}
});
});
</script>
C#
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object BranchFill(string Zone)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Branch = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch(Zone, "", "SelectBranch");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Branch.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Code"].ToString()
});
}
return Branch;
}
else
{
return "false";
}
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static Object EmployeeFill(string Branch)
{
string result = string.Empty;
var obj = new Reports();
List<ListItem> Employee = new List<ListItem>();
DataTable dt = obj.CS.StaticZoneBranch("", Branch, "SelectEmployee");
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
Employee.Add(new ListItem
{
Text = dt.Rows[i]["Name"].ToString(),
Value = dt.Rows[i]["Employee Id"].ToString()
});
}
return Employee;
}
else
{
return "false";
}
}
And the button Click(which is not working)
protected void Button1_Click(object sender, EventArgs e)
{
ReportClass RC = new ReportClass();
if (ddZone.SelectedValue !="0")
{
RC.Zone = ddZone.SelectedValue;
RC.Branch = ddBranch.SelectedValue;
RC.EmployeeId = ddEmployee.SelectedValue;
Report = RC.GetReport();
}
}
Why this click function is not Working, please help me to know..
I have a WebMethod which gets data that I want to fill DropDown with in a DataSet.
Currently I am filling the dropdown using a hardcoded object. But I want to replace this hard coded object with data returned by webmethod.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return ds.GetXml();
}
CLIENT SIDE(UPDATE 1):
<script type = "text/javascript">
function GetDropDownData() {
var myDropDownList = $('.myDropDownLisTId');
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(jQuery.parseJSON(data.d), function () {
myDropDownList.append($("<option></option>").val(this['FieldDescription']).html(this['FieldCode']));
});
},
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(response) {
console.log(response.d);
alert(response.d);
}
</script>
function GetDropDownData() {
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: '{name: "abc" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data.d)
{
$.each(data.d, function (){
$(".myDropDownLisTId").append($("<option />").val(this.KeyName).text(this.ValueName));
});
},
failure: function () {
alert("Failed!");
}
});
}
var theDropDown = document.getElementById("myDropDownLisTId");
theDropDown.length = 0;
$.each(items, function (key, value) {
$("#myDropDownLisTId").append($("<option></option>").val(value.PKId).html(value.SubDesc));
here "SubDesc",PKId describes the value getting out of Database., u need to separate your value from dataset.
From the WebMethod, don't send DataSet directly, send XML...
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
DataSet ds = new DataSet();
ds.Tables.Add("Table0");
ds.Tables[0].Columns.Add("OptionValue");
ds.Tables[0].Columns.Add("OptionText");
ds.Tables[0].Rows.Add("0", "test 0");
ds.Tables[0].Rows.Add("1", "test 1");
ds.Tables[0].Rows.Add("2", "test 2");
ds.Tables[0].Rows.Add("3", "test 3");
ds.Tables[0].Rows.Add("4", "test 4");
return ds.GetXml();
}
Before Ajax call...
var myDropDownList = $('.myDropDownLisTId');
Try like below...(inside Ajax call)
success: function (response) {
debugger;
$(response.d).find('Table0').each(function () {
var OptionValue = $(this).find('OptionValue').text();
var OptionText = $(this).find('OptionText').text();
var option = $("<option>" + OptionText + "</option>");
option.attr("value", OptionValue);
myDropDownList.append(option);
});
},
Note:
OptionValue and OptionText are the Columns of DataSet Table.
$(response.d).find('Table0').each(function (){}) - Here Table0
is the name of Table inside DataSet.
[System.Web.Services.WebMethod]
public static string GetDropDownDataWM(string name)
{
//return "Hello " + name + Environment.NewLine + "The Current Time is: "
// + DateTime.Now.ToString();
var msg = "arbaaz";
string[] name1 = new string[1];
string[] Value = new string[1];
name1[0] = "#Empcode";
Value[0] = HttpContext.Current.Session["LoginUser"].ToString().Trim();
DataSet ds = new DataSet();
dboperation dbo = new dboperation();
ds = dbo.executeProcedure("GetDropDownsForVendor", name1, Value, 1);
return DataSetToJSON(ds);
}
public static string DataSetToJSON(DataSet ds)
{
Dictionary<string, object> dict = new Dictionary<string, object>();
foreach (DataTable dt in ds.Tables)
{
object[] arr = new object[dt.Rows.Count + 1];
for (int i = 0; i <= dt.Rows.Count - 1; i++)
{
arr[i] = dt.Rows[i].ItemArray;
}
dict.Add(dt.TableName, arr);
}
var lstJson = Newtonsoft.Json.JsonConvert.SerializeObject(dict);
return lstJson;
}
Ajax Call
function GetAssociation() {
var myDropDownList = $("#myDropDownLisTId");
var post_data = JSON.stringify({ "name": "xyz"});
$.ajax({
type: "POST",
url: "test.aspx/GetDropDownDataWM",
data: post_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
json_data = JSON.parse(response.d);
myDropDownList.empty();
for(i=0; i<json_data.Table.length; i++)
{
myDropDownList.append($("<option></option>").val(json_data.Table[i][0]).html(json_data.Table[i][1]));
}
},
failure: function (response) {
alert(response.d);
}
});
}
// We can bind dropdown list using this Jquery function in JS script
function listDropdownBind() {
var requestId = 123;
$.ajax({
type: "POST",
url: "/api/ControllerName/ActionName?param=" + param, // call API with parameter
headers: { 'rId': requestId },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var optionhtml1 = '';
var optionhtml1 = '<option value="' +
0 + '">' + "--Select--" + '</option>';
$("#ddlName").append(optionhtml1);
$.each(data, function (i) {
var optionhtml = '<option value="' +
data.d[i].Value + '">' + data.d[i].Text + '</option>';
$("#ddlName").append(optionhtml);
});
}
});
};
I have a function in javascript and I send a json to c# by Ajax, but when I receive in c#, it's not a json. How I do it? If i put Response.Write(arr) in c#, the response is System.string[]. My project is in MVC 3
Function c#
public int salvar(string[] arr)
{
SqlConnection conexao = new SqlConnection(WebConfigurationManager.ConnectionStrings["strConexao"].ToString());
conexao.Open();
SqlTransaction trx = conexao.BeginTransaction();
try
{
//Truncate cliente_recurso
//BUProjetosDAL dal = new BUProjetosDAL();
// dal.excluirClientesRecurso(conexao, trx);
dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter tabela = new dtsRecursoClienteTableAdapters.RECURSO_CLIENTETabelaTableAdapter();
for (int j = 0; j <= 149; j++) { // <- here
tabela.Insert(arr);
}
trx.Commit();
return 1;
}
catch (SqlException ex)
{
try
{
trx.Rollback();
return 0;
}
catch (Exception exRollback)
{
return 0;
}
}
}
Function js + ajax
$("#btnSalvar").on("click", function () {
var confirma = confirm("Deseja salvar os dados?");
if (confirma) {
var lista = jQuery("#tabelaRecurso").getDataIDs();
var total = lista.length;
var arr = [];
for (var i = 1; i <= lista.length; i++) {
var rowData = $("#tabelaRecurso").jqGrid('getRowData', i);
if (rowData.CD_CLIENTE != 0) {
arr[i - 1] = {
col1: rowData.CD_RECURSO,
col2: rowData.NM_RECURSO,
col3: rowData.CD_CLIENTE,
col4: rowData.LISTA_EMAIL,
col5: rowData.LISTA_EMAIL_COPIA
}
}
}
$.ajax({
type: 'POST',
url: '/Paginas/salvar',
contentType: "application/json; charset=utf-8",
data: JSON.stringify(arr),
dataType: 'json',
success: function (dados) {
if (dados == 0) {
alert("Nao foi possivel salvar os dados");
}
}
});
}
});
Try using
$.ajax({
type: 'POST',
url: '/Paginas/salvar',
contentType: "application/json; charset=utf-8",
data: arr,
dataType: 'json',
traditional: true, --> use the traditional object serialization for the array
success: function (dados) {
if (dados == 0) {
alert("Nao foi possivel salvar os dados");
}
}
});
the code:
[WebMethod]
public static string [] GetMorechatMsgs(int toclient, int fromclient, int top)
{
string [] List =new string[2];
int chatcount = new ChatPage().GetAllMsgCount(toclient, fromclient);
if (top <= chatcount)
{
string toreturn=new ChatPage().GetChat(fromclient, toclient, "", top);
List[0]= toreturn;
List[1] = chatcount.ToString();
}
else {
List = null;
}
return List;
}
html:
$.ajax({
type: "POST",
url: "ChatPage.aspx/GetMorechatMsgs",
data: "{'toclient':'" + ToClient + "','fromclient': '" + fromClient + "','top': '" + $("#MsgCount").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != "") {
// how to read the returned table
}
else {
}
},
error: function (xhr) {
alert("responseText: " + xhr.responseText);
}
});
How can i read the returned string array on success ?
serialize the list of your string i.e
change your method to this:
[WebMethod]
public static string GetMorechatMsgs(int toclient, int fromclient, int top)
{
/// your usual code
return new JavaScriptSerializer().Serialze(list);
}
and read returned data like this:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
console.log(jsonData[i]);
}
}
The WebMethod will return your string array in the form ["string", "string", "string", ...], therefore, simply loop through the array in the way Manish demonstrated:
success: function (data) {
var jsonData =$.parseJSON(data.d);
for(var i=0; i<jsonData.length; i++){
var theString = jsonData[i];
//Do something with the string
}
}
I have two ASP ListBoxes. As you can see below, lbAvailable is populated on PageLoad with WebMethod and populates all cities. LbChoosen is populated depending on DropDown Value Chosen. The Dropdown has 4 options(ALL, Top25, Top50, Top100). for example if you choose Top 25 which is value 4, lbChosen populates top 25 cities (This all works).
MY PROBLEM IS lbAvaliable always populates all cities. So if i chose top 25 which populates top25 cities into lbChoosen, how can those value (top25 cities) be removed from lbAvailable
function LoadMarketsAvailableJS() {
var ddlFootprint = $('#ddlFootprint');
var lbChoosen = $('#lbChoosen');
var lbAvailable = $('#lbAvailable');
lbChoosen.empty();
var SelectedMarkets = [];
var url = "";
//Load lbAvailable on Page Load with all Markets
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Campaign.aspx/LoadAvailableMarkets",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
$("#lbAvailable").append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function(result) {
alert("Error");
}
});
//Check DropdownList
if (parseInt(ddlFootprint.val()) == 1) {
url = 'Campaign.aspx/LoadAvailableMarkets';
} else if (parseInt(ddlFootprint.val()) == 2) {
url = 'Campaign.aspx/LoadTop100Markets';
}
else if (parseInt(ddlFootprint.val()) == 3) {
url = 'Campaign.aspx/LoadTop50Markets';
}
else if (parseInt(ddlFootprint.val()) == 4) {
url = 'Campaign.aspx/LoadTop25Markets';
}
else if (parseInt(ddlFootprint.val()) == 5) {
url = 'Campaign.aspx/LoadAvailableMarkets';
}
//Load Select Dropdown Value to lbChoosen
if (url.length > 0) {
$.ajax({
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
},
complete: function (jqXHR, textStatus) {
}
});
}
}
Assuming I've understood what you're asking, if you want to remove options from lbAvailable as they're added to lbChoosen you should be add the following line:
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
So your code will look something like:
success: function (msg) {
var obj = $.parseJSON(msg.d);
for (var i = 0; i < obj.Markets.length; i++) {
if (SelectedMarkets.indexOf(obj.Markets[i].id.toString()) == -1) {
lbChoosen
.append($("<option></option>")
.attr("value", obj.Markets[i].id)
.text(obj.Markets[i].name + " - " + obj.Markets[i].rank));
lbAvailable.find('option[value="' + obj.Markets[i].id + '"]').remove();
}
}
},