I have one function in my code behind
[System.Web.Services.WebMethod]
public static pcpName[] getPcpNames(string pcpCounty, string claimType)
{
List<pcpName> pcpNames = new List<pcpName>();
string query = "SELECT DISTINCT [PCP_ID], [PCP_NAME]+':'+[PCP_ID] AS [PCP_NAME] FROM [dbo].[FreedomTrinity] WHERE [PCP_COUNTY] = '" + pcpCounty + "' AND [CLAIM_TYPE] = '" + claimType + "'";
SqlDataReader reader = Database.SQLRead(query);
while (reader.Read())
{
pcpName names = new pcpName();
names.PCP_ID = reader.GetString(0);
names.PCP_NAME = reader.GetString(1);
pcpNames.Add(names);
}
return pcpNames.ToArray();
}
Now I want to populate items in a drop down list using this out put using jQuery.
So I write the code like this in my js file.
$(document).ready(function () {
$("#drpPcpCounty").change(function () {
//Remove items from drpPcpName
$("#drpPcpName option").remove();
$.ajax({
type: "POST",
url: "FreedomContestation.aspx/getPcpNames",
data: '{pcpCounty: "' + $("#drpPcpCounty").val() + '", claimType: "' + $("input:radio[name='rbtnlstClaimType']:checked").val() + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
response($.map(data.d, function (item) {
for (i in data) {
var d = data[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
}))
},
failure: function (response) {
alert(response.d);
}
});
});
});
But nothing is happening in dropdown list. Code behind code is returning the array with values. What to do after success: ??
EDIT 1
I track the code till response($.map(data.d, function (item) { . But I don't know what's happening inside it. No alert() working inside response($.map(data.d, function (item) {
Try this:
success: function (data) {
for (var i = 0;i < data.d.length;i++) {
var d = data.d[i];
$('#drpPcpName').append($("<option></option>").attr("value", d.PCP_ID).text(d.PCP_NAME));
}
},
Related
Ok I have created a tab with a table inside of it as follows -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST", url: "../WebMethods/MarketPersuitMethods.aspx/GetColumnHeaders",
dataType: "json",
contentType: "application/json",
success: function (res) {
$.each(res.d, function (data, value) {
$tbody.append("<th>" + value.ColumnsName + "</th>");
});
$tbody.append('<tr />').children('tr:last')
setTimeout(function () {
}, 1000);
}
});
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
//$table.appendTo('#TabbedMktList');
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
Here is my C# Code
[WebMethod(EnableSession = true)]
public static string GetQueryInfo()
{
String daresult = null;
DataTable yourDatable = new DataTable();
string strConnString = WebConfigurationManager.ConnectionStrings["TimeClock"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlCommand cmd = new SqlCommand();
SqlDataAdapter da = new SqlDataAdapter();
cmd.CommandText = "select * from OCI_TEXT_PROJECT_MASTER where proj_id=2049";
da.SelectCommand = cmd;
cmd.CommandTimeout = 30;
cmd.Connection = con;
con.Open();
da.Fill(yourDatable);
daresult = DataSetToJSON(yourDatable);
return daresult;
}
public static string DataSetToJSON(DataTable table)
{
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(table);
return JSONString;
}
It is creating the column headers as I wish for it to do. However, I need to populate all the JSON data for the rows below it. I would not know the column headers as they can change.
I am able to see my results are coming back in JSON data -
[{"Project ID":"18180","OPRN":null,"Proj_Type":"2049","Client Name":null,"client_id":null,"ClientContact":null,"Contact_ID":null,"PN":null,"CompleteDate":"2020-05-21T00:00:00","cost":null,"SQFT":2000,"BIM":null,"LEED":"NO ","Delivery_Meth":"Corey ","City":"Orlando","State":"FL ","County":"Orange","IT":"1141","Project Name":null,"Address":"1234. Orlando Ave","zip":"12345","notes":"<p class=\"MsoNormal\"><b>EXTRA TESTING 1-2-3-43</b></p>","PM":"1141","OLDOWNER":null,"Owner_Contact":null,"ProjectManager":"Corey ","Architect":"Collier Health Services","ContractorORG":"BVW Development","ArchitectID":929,"PNAME":"OCI DYNAMICS CRM PROJECT MANAGEMENT SOFTWARE","PROJ_ID":2049,"Office":"Maitland","MPROJECT":null,"Contractor":930,"addr2":"","PROJSTATUS":2,"TotalProjectTime":null,"corp":"0","ProjectStatus":"Construction","TotalDesignTime":null,"OFFNUM":1,"Owner":null,"ProjectType":null,"MarketSector":"FINANCIAL","users":"1141","team":null,"BuildingType":null,"ETA":null,"designstartdate":null,"FINALCONTRUCT":24000.0000,"ESTCONSTRUCT":15000.0000,"Units":"12","WebType":"P","RequestedBy":null,"RequestedDate":null,"Status":"Interview","RFPDATE":null,"SENTDATE":null,"InterviewDate":null,"OCIDATE":null,"Method":null,"ContractType":"0","ContractName":null,"Tags":"CRM FINANCIAL NewTest rigtest2","TotalProfit/Loss":3,"Disciplines":"Mechanical, CAD, Clerical, QA/QC, Project Management","ChillerType":"1","Revit":"2017","Tons":145,"Rooms":5}]
However -
I have no idea where to get it to map over automatically.
I would ideally think somehow to map it based on the TH header text because they would be the same.
My issue is somewhere in here
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (data) {
//HERE IS MY ISSUES
$tbody.append("<td>" + value.ColumnsName + "</td>");
}
});
Figured it out -
function createTab(Name, id) {
var $button = $('<button/>', {
'class': 'tablinks',
'onclick': 'return false;',
'id': name,
text: Name,
click: function () {
return false;
}
});
var $div = $('<div>').prop({
id: Name,
'name': id + 'MKTTAB',
className: 'tabcontent'
})
var $table = $('<table cellspacing="0" rules="all" class="RFPGRID" style="border-color:Black;border-width:1px;border-style:Solid;border-collapse:collapse;">');
$table.append('<caption>' + Name + '</caption>')
var $tbody = $table.append('<tbody />').children('tbody');
$tbody.append('<tr />').children('tr:last');
$.ajax({
type: "POST",
url: "../WebMethods/MarketPersuitMethods.aspx/GetQueryInfo",
data: {},
contentType: "application/json; charset=utf-8",
dataType: 'json',
success: function (d) {
var data = $.parseJSON(d.d);
var colHeader = Object.keys(data[0]);
for (var i = 0; i < colHeader.length; i++) {
$tbody.append("<th>" + colHeader[i] + "</th>");
}
//sets new line
$tbody.append('<tr />').children('tr:last')
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < colHeader.length; j++) {
$tbody.append('<td>' + data[i][colHeader[j]] + '</td>');
}
$tbody.append('<tr />').children('tr:last')
}
setTimeout(function () {
}, 1000);
}
});
$button.appendTo('#tabs');
$table.appendTo($div);
$div.appendTo('#TabbedMktList');
}
Hi i am trying to navigate through anchor link. Only the first link works. For example if i click a link in a page it goes to that link, but when there is another link in page whcih i have clicked it doesnt work. And also the second has the same class 1st link Please help.
$('#frmDisplay').on('load', function () {
$('#frmDisplay a.anchorLink').on('click', function () {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d);
},
error: function (response) {
alert(response.responseText);
}
});
});
});
public static string getlink(int Id)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["connString"].ConnectionString);
string link = "extlink";
BookTree obj = new BookTree();
DataSet ds = obj.getlink(Id);
SqlCommand cmd=new SqlCommand("select vcFilePath from tblBookNodes where iModuleId='" + Id + "'",conn);
conn.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
bytes = (byte[])dr["vcFilePath"];
}
string fileName = link.Replace(" ", "_") + ".htm";
// DirectoryInfo strPath = new DirectoryInfo(HttpContext.Current.Server.MapPath(#"~/Linking/"));
//string strPath = HttpContext.Current.Server.MapPath(#"/Linking/") + fileName;
//foreach (FileInfo file in strPath.GetFiles())
//{
// file.Delete();
//}
string path = Path.Combine(HttpContext.Current.Server.MapPath("~/htmlFile/"), fileName);
var doc = new HtmlDocument();
string html = Encoding.UTF8.GetString(bytes);
doc.LoadHtml(html);
StringWriter sw = new StringWriter();
var hw = new HtmlTextWriter(sw);
StreamWriter sWriter = new StreamWriter(path);
sWriter.Write(sw.ToString());
doc.Save(sWriter);
sWriter.Close();
//string fileContents = html;
//System.IO.File.WriteAllText(path, html);
return File.ReadAllText(path);
}
You have to use "on" instead of find() and event listener attach.
Please refer to this example:
$('#formDisplay a.anchroLink').on('click', function() {
// TODO: handle the click
})
This is necessary because when you add the event listener the DOM is not yet ready to handle requests for non existing content. Using "on" you can attach an event to a class or a simple DOM query.
To be more clear I post your code with modifications based on my previous suggestion:
$('#frmDisplay a.anchorLink').on('click', function () {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d)
},
error: function (response) {
alert(response.responseText);
}
});
});
My last answer (I don't know you were using iFrames):
function clickHandler() {
var id = $(this).attr('id');
var hid = document.getElementById('<%= HiddenField1.ClientID %>');
hid.value = id;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Amm.aspx/getlink",
data: "{'Id': '" + id + "'}",
dataType: "json",
success: function (data) {
$('#frmDisplay').contents().find('html').html(data.d);
// You can reload the event handler because the prev one
// has been lost after refreshing the page with the ajax call.
$('#frmDisplay').contents()
.find('a.anchorLink')
.click(clickHandler);
},
error: function (response) {
alert(response.responseText);
}
});
}
$('#frmDisplay').on('load', function () {
$('#frmDisplay')
.contents()
.find('a.anchorLink')
.on('click', clickHandler);
})
I am trying to fetch company data based on company id through ajax and fill the related textboxes with the received data. Company id is selected through ajax autocomplete. The code was working fine two days back and suddenly it started generating an error for only first two entries of autocomplete and for rest it is working fine. Can anyone point out the mistake in this. Thank you.
Error Details: "Message":"A circular reference was detected while serializing an object of type \u0027System.Data.Entity.DynamicProxies.Company_81625299B5B4D7A3375D55E48BE84921728B8D48335366DF8CA6844A8D10FF5D\u0027.","StackTrace":" at System.Web.Script.Serialization.JavaScriptSerializer.SerializeValueInternal(Object o, StringBuilder sb, Int32 depth, Hashtable objectsInUse, SerializationFormat serializationFormat, MemberInfo currentMember)\r\n.
Below is my code:
function setCompanyData(pageurl, txtboxid, txtResultid) {
var temp = true;
var searchTbox = $jq14("[id$=" + txtboxid + "]");
var resultTbox = $jq14("[id$=" + txtResultid + "]");
searchTbox.autocomplete({
source: function (request, response) {
$jq14.ajax({
url: pageurl,
data: "{ 'SearchText': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data.d, function (item) {
return {
label: item.split('*')[0],
val: item.split('*')[1]
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
autoSelect: true,
autoFocus: true,
select: function (e, i) {
// e.preventDefault();
searchTbox.val(i.item.label);
resultTbox.val(i.item.val).trigger('change');
temp = true;
// return false;
},
change: function (e, i) {
var cId = resultTbox.val();
if (isEmptyOrSpaces(cId)) {
// error
cId = 0;
searchTbox.val("").trigger('');
}
if (isEmptyOrSpaces(searchTbox.val())) {
// error
cId = 0;
resultTbox.val("").trigger('change');
}
getCompanyDetails(cId);
},
minLength: 0
}).focus(function () {
if (temp) {
$jq14(this).autocomplete("search", "");
temp = false;
}
});
searchTbox.autocomplete("widget").addClass("fixedHeight");}
function getCompanyDetails(cid) {
$jq14.ajax({
url: "/sw/adm/update-delete-company.aspx/GetCompanyData",
data: "{ 'cId': '" + cid + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
beforeSend: function () {
$('#loader').show();
},
complete: function () {
$('#loader').hide();
$("#messageBox").hide().slideDown();
setTimeout(function () {
$("#messageBox").fadeOut();
}, 5000);
},
success: function (result) {
$jq14('#cphMainLeft_txtAddress').val(result.d.CompanyAddress);
$jq14('#cphMainLeft_txtCountry').val(result.d.CompanyCountry);
$jq14('#cphMainLeft_txtCity').val(result.d.CompanyCity);
$jq14('#cphMainLeft_txtNewCompanyName').val(result.d.CompanyName);
$jq14('#cphMainLeft_txtEmail').val(result.d.CompanyEmail);
$jq14('#cphMainLeft_txtPanNo').val(result.d.CompanyPAN);
$jq14('#cphMainLeft_txtTinNo').val(result.d.CompanyTIN);
$jq14('#cphMainLeft_txtPhone').val(result.d.CompanyPhone);
$jq14('#cphMainLeft_txtPincode').val(result.d.CompanyPincode);
$jq14('#cphMainLeft_hfTxtCountry').val(result.d.CompanyCountry);
$jq14("#cphMainLeft_ddlCompanyType").val(result.d.CompanyType);
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
}
C# Webmethod goes like:
[WebMethod]
public static Company GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord != null)
return companyRecord;
else
return new Company();
}
Thank you Ashokkumar M. Prajapati for providing the hint.
Instead of returning Company object from [WebMethod], I have converted the company object to Json string in code behind and returned it.
Here is my WebMethod:
[WebMethod]
public static string GetCompanyData(int cId)
{
Entities db = new Entities();
var companyRecord = (from cmp in db.Companies
where cmp.CompanyId == cId
select cmp).SingleOrDefault();
if (companyRecord == null)
companyRecord = new Company();
string s = string.Empty;
s = JsonConvert.SerializeObject(companyRecord,
new JsonSerializerSettings
{
ReferenceLoopHandling = ReferenceLoopHandling.Ignore
});
return s;
}
Then I updated the success method of getCompanyDetails(cid) to:
success: function (result) {
res = JSON.parse(result.d);
$jq14('#cphMainLeft_txtAddress').val(res['CompanyAddress']);
$jq14('#cphMainLeft_txtCountry').val(res['CompanyCountry']);
$jq14('#cphMainLeft_txtCity').val(res['CompanyCity']);
$jq14('#cphMainLeft_txtNewCompanyName').val(res['CompanyName']);
$jq14('#cphMainLeft_txtEmail').val(res['CompanyEmail']);
$jq14('#cphMainLeft_txtPanNo').val(res['CompanyPAN']);
$jq14('#cphMainLeft_txtTinNo').val(res['CompanyTIN']);
$jq14('#cphMainLeft_txtPhone').val(res['CompanyPhone']);
$jq14('#cphMainLeft_txtPincode').val(res['CompanyPincode']);
$jq14('#cphMainLeft_hfTxtCountry').val(res['CompanyCountry']);
$jq14("#cphMainLeft_ddlCompanyType").val(res['CompanyType']);
}
and it worked wonderfully. Thanks again.
Hi I have this code below
How could I pass preferably 1 array which will contain an ID number and a value from a textbox which is dynamically generated and then passed to the backend to C#
var listoftextboxesWithValues = new Array();
var listoftextboxesWithID = new Array();
var i = 0;
$.each(listOftxtPriceTypeID, function (index, value) {
listoftextboxesWithID[i] = value.ID.toString();
listoftextboxesWithValues[i] = $("#txtPriceTypeID" + value.ID).val().toString();
i++;
});
//---Till here the data in the above arrays is as expected, the problem starts below in the data :
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data: "{subCategoryID : '" + parseInt(subcategoryID) + "',name: '" + name + "',description: '" + description + "',quantity: '" + parseInt(quantity) + "',supplier: '" + supplier + "',vatRate: '" + parseFloat(VatRate) + "',colorID: '" + parseInt(colorID) + "',brandID: '" + parseInt(brandID) + "',imagePath: '" + fileNameGUID + "',listOfTextBoxes: '" + JSON.stringify(listoftextboxesWithValues) + "',listOfTextBoxesValues: '" + JSON.stringify(listoftextboxesWithID) + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
[WebMethod]
public static void StoreNewProduct(int subCategoryID, string name, string description, int quantity,
string supplier, float vatRate, int colorID, int brandID, string imagePath, string[] listOfTextBoxesID, string[] listOfTextBoxesValues )
{
Product p = new Product();
ProductPriceType ppt = new ProductPriceType();
p.CategoryID = subCategoryID;
p.Name = name;
p.Description = description;
p.Quantity = quantity;
p.Supplier = supplier;
// p.VATRate = vatRate;
p.ColorID = colorID;
p.BrandID = brandID;
p.Image = imagePath;
//...
}
Any help would be much appreciated
if I will do it, my approach is to seperate those two,
create string array for texts
create string array for values
i believe that the number of values will be the same with texts since it is generated dynamically.
then pass those two string arrays in c# backend.
you can use json2.js is cool ,I used this
var valueObj = { field1: $("input[name=field1]").val(),
field2: $("input[name=field2]").val()}
and then I can parse with this:
JSON.stringify(valueObj)
in the ajax call you can use like this
$.ajax({
type: "POST",
url: "/MemberPages/AdminPages/AdminMainPage.aspx/StoreNewProduct",
data:valueObj ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("oh yeh");
},
error: function (error) {
alert("An Error Occured");
}
});
//In JS file
var arr = [];
arr.push( $("#textZipcode").val());
arr.push( $("#textPhone").val());
arr.push($("#textAddress").val());
arr.push( $("#textMobile").val());
//You can add any number. It will store to array properly.
$.ajax({
type: "POST",
url: "HomePage.aspx/SaveData",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:JSON.stringify({arr:arr}),
success: function (response) {
}});
//In C#
[WebMethod]
public static void SaveData(string[] arr)
{
}
I have a simple web service with one argument :
public static string LoadComboNews(string id)
{
string strJSON = "";
DataRowCollection people = Util.SelectData("Select * from News where person = "+ id +" Order by NewsId desc ");
if (people != null && people.Count > 0)
{
//temp = new MyTable[people.Count];
string[][] jagArray = new string[people.Count][];
for (int i = 0; i < people.Count; i++)
{
jagArray[i] = new string[] { people[i]["NewsID"].ToString(), people[i]["Title"].ToString() };
}
JavaScriptSerializer js = new JavaScriptSerializer();
strJSON = js.Serialize(jagArray);
}
return strJSON;
}
on javascript I am trying to call it with parameter :
jQuery.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: "{'id':usrid}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
combonews = eval(msg.d);
}
});
UPDATE:
usrid is dynamic
Am I doing something wrong here?
data you are sending is invalid "{'id':usrid}"
this not a valid json
probably what you wanna do is assuming usrid is a variable
"{\"id\":"+usrid+"}"
with it shoudnt you be executing this command
Select * from News where person = '"+ id +"' Order by NewsId desc
Considering id is a string
also try this
combonews = JSON.stringify(msg);
Add WebMethod to the method
[WebMethod]
public static string LoadComboNews(string id)
And try this format
$.ajax({
type: "POST",
url: "webcenter.aspx/LoadComboNews",
data: '{"id":"usrid"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
// Replace the div's content with the page method's return.
alert(msg.d);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
alert(textStatus + " " + errorThrown);
}
});
Or
data: '{"id":"' + usrid + '"}',