I've this code which I'm using to post a message on 'Enter' key press, but it's going on loop and instead of posting one message it's posting it multiple times randomly.
This is the function I'm calling in on <input id='txtsendmsg" + i + "' placeholder=\"Write a comment...\" onkeypress='PostMessage(event,"+i+");' class='msgtxt'></input> any help would be appreciated.
function PostMessage(event,key) {
$('#txtsendmsg'+key).on("keypress", function (e) {
if (e.which == 13) {
var msgid = $(this).siblings('.msgid').val();
var msgtxt = $(this).val();
$.ajax({
url: "student_post_login.aspx/funPostMessage",
data: 'postd=' + "Y" + '&msgid=' + msgid + '&msgtxt=' + msgtxt,
success: function (data) {
if (data) {
displayData();
}
},
failure: function (response) {
alert("Faliure:");
},
error: function (response) {
alert(response);
}
});
e.preventDefault();
}
});
}
The problem is because you are attaching an event handler every time you hit the a key in the input field. Press a key twice and you get two requests sent, three times; three and so on.
Try assigning the handler using jQuery only instead of the onclick attribute:
<input id='txtsendmsg" + i + "' placeholder=\"Write a comment...\" class='msgtxt' />
$('.msgtxt').on('keypress', function (e) {
var $el = $(this);
if (e.which == 13) {
var msgid = $el.siblings('.msgid').val();
var msgtxt = $el.val();
$.ajax({
url: "student_post_login.aspx/funPostMessage",
data: 'postd=' + "Y" + '&msgid=' + msgid + '&msgtxt=' + msgtxt,
success: function (data) {
if (data) {
displayData();
}
},
failure: function (response) {
alert("Faliure:");
},
error: function (response) {
alert(response);
}
});
e.preventDefault();
}
});
Related
I have a tagit auto-complete jquery which runs fine when searching case numbers. I'm trying to append some case numbers already inserted in the text box from code behind and set as individual tags for case number. It does set as a tag, but I'm unable to make individual tags as it combines all case numbers to a single tag. Below is my code.
class.cs
List<Models.Case> caseRefer = CaseCon.ViewById(SelectedCase.strId); // here I'm fetching case numbers from database with ',' for separation.
List<string> casenumbers = new List<string>();
if (caseRefer[0].ReferCases!=null)
{
if (caseRefer[0].ReferCases != null)
{
casenumbers = caseRefer[0].ReferCases.Split(',').ToList(); // here I'm spiting case numbers
}
foreach (var item in casenumbers)
{
if (!item.Contains("<br />"))
{
txt_referCases.Text += item + Environment.NewLine; // here I'm trying to make all case numbers an individual tags but new line is not making any difference.
}
}
}
.aspx
<asp:TextBox ID="txt_referCases" runat="server"></asp:TextBox>
<script>
$(function () {
var arr = [];
var arrName = [];
$('#<%=txt_referCases.ClientID %>').tagit({
autocomplete: {
delay: 0,
minLength: 3,
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Case.aspx/ReferCases") %>',
data: "{ 'caseNum': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
arr = $.map(data.d, function (el) { return el });
response($.map(data.d, function (item, index) {
return {
label: item,
val: index
}
}))
},
error: function (response) {
alert(response.responseText);
},
failure: function (response) {
alert(response.responseText);
}
});
},
}
});
});
</script>
Finally solved my own problem. It was just a matter of replacing Environment.NewLine to ',' would do the job. So the line would be
txt_referCases.Text += item + ","
and this will separate the tags.
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.
Anyone can tell me how can i use tokenizing in auto-complete for multiple selection, I am make you sure that, i want only with asp.net web from web service
My Code:
$(function () {
// Web servcice javascript code for City
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{ 'username': '" + request.term + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.d.length > 0) {
response($.map(data.d, function (item) {
return {
label: item.split('-')[0],
val: item.split('-')[1]
};
}))
} else {
response([{ label: 'No results found.', val: -1 }]);
}
}
});
},
select: function (e, u) {
if (u.item.val == -1) {
return false;
}
}
});
});
I want to use a web service to fetch data from database and show on front-end for multiple selection
Web Service:
DataTable dt = userRegistrationHelper.GetSkillsList(username);
DataRow[] rows = null;
rows = dt.Select(string.Format("SkillName = {0}", username));
string[] result = new string[rows.Length];
for (int i = 0; i <= rows.Length - 1; i++)
{
result[i] = rows[i]["SkillName"].ToString();
}
return result;
Autocomplete with multiple words or values with comma separated
$(function () {
$("[id*=ctl00_ContentMain_TextBoxSkills]").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<%=ResolveUrl("~/WebServices/WebServiceSkills.asmx/GetAutoCompleteData")%>',
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("[id*=ctl00_ContentMain_TextBoxSkills]").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
});
Using .NET here's what I've got.. The right results are returned, but they're all combined together into one long string. How can I make it so I can select one item at a time from the results returned? I know my source in the javascript is configured incorrectly. Any help would be appreciated. Thanks
Code behind:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string[] GetEmails(string emailContains)
{
LoginSet logins = staticLogic.searchLogins(staticClient, new SearchCriteriaSet());
List<BaseEntry> loginList = logins.Where(x => ((LoginEntry)x).LoginEMail.Contains(emailContains)).ToList();
List<string> emails = new List<string>();
for (int i = 0; i < loginList.Count(); ++i)
{
string email = ((LoginEntry)loginList.ElementAt(i)).LoginEMail;
emails.Add(email);
}
//JavaScriptSerializer serializer = new JavaScriptSerializer();
//string json = serializer.Serialize(emails.ToArray());
return emails.ToArray();
}
UI:
<tr><td>Destination:</td>
<td>
<div class="ui-widget">
<input type="text" name="EMailReportDestination" id="EMailReportDestination" size="60" runat="server" />
</div>
</td>
</tr>
JQuery:
$('#EMailReportDestination').autocomplete({
source: function (request, response) {
$.ajax({
url: '/reports/editemailreport.aspx/GetEmails',
type: 'POST',
dataType: 'json',
data: "{'emailContains':'" + request.term + "'}",
contentType: "application/json; charset=utf-8",
dataFilter: function (data) { return data; },
success: function (data) {
//console.log('autocomplete success: ' + data);
response($.map(data, function (item) {
return {
label: item,
value: item
}
}));
},
error: function (xhr, ajaxOptions, thrownError) {
console.log("autocomplete error: " + xhr.status + ", " + thrownError);
}
});
},
minLength: 2,
select: function (event, ui) {
console.log(ui.item ? "selected: " + ui.item.label : "nothing selected, input was " + this.value);
},
open: function () {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function () {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});
I tried and I don't know array returned in data.d. try to change
response($.map(data, function (item)
to
response($.map(data.d, function (item)
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));
}
},