why autocomplete textbox textchange event not firing? - asp.net

I have a textbox with ajax jquery autocomplete feature.but the textchange event is not firing.
<asp:TextBox ID="txtNumber" runat="server" width="98%" OnTextChanged="txtNumber_TextChanged" AutoPostBack="true" ></asp:TextBox>
Autocomplete function:
function QuoteNumber(sender, args) {
$(function () {
$("#<%=txtNumber.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Webservice.asmx/GetNumberForAutocomplete") %>',
data: "{ 'prefix': '" + request.term + "'}",
dataType: "json",
type: "POST",
async: false,
mustMatch: true,
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) {
},
failure: function (response) {
}
});
},
select: function (e, i) {
$("#<%=hdnNumber.ClientID %>").val(i.item.val);
if (i.item.val == "No Records Found") {
$("#<%=hdnNumber.ClientID %>").val(-1);
document.getElementById('<%=txtNumber.ClientID%>').value = "";
return false;
}
},
minLength: 0
}).bind('focus', function () { $(this).autocomplete("search"); });
});
}

<script type="text/javascript">
$(document).ready(function () {
$("#<%=txtSearch.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: '<%=ResolveUrl("~/Service.asmx/GetCustomers") %>',
data: "{ 'prefix': '" + 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);
}
});
},
select: function (e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
$("#<%=hfCustomerName.ClientID %>").val(i.item.value);
$("[id*=btnSubmit]").click();
},
minLength: 1
});
});

Add to end of select callback this line: __doPostBack('<%= txtNumber.UniqueID %>', '');

In addition to above answer we need to below code snippest in Select:
select: function (e, i) {
$("#<%=hfCustomerId.ClientID %>").val(i.item.val);
$("#<%=hfCustomerName.ClientID %>").val(i.item.value);
$("[id*=btnSubmit]").click();
$("#<%=txtNumber.ClientID %>").val(i.item.value);
__doPostBack('<%= txtNumber.UniqueID %>', '');
},

Related

How to fix the INSERT statement conflicted with the foreign key constraint when I call ajax

I use ajax to create new Color (id, name) and Size (id, name) and I get their id, quantity in a row to Quantities table but checking database, they do not appear and get error.
I got size, color data when I call ajax but when I check SQL Server, it does not have their id.
$("#btnSaveQuantity").on('click', function () {
var quantityList = [];
$.each($('#table-quantity-content').find('tr'), function (i, item) {
var size = $(item).find('input.txtSize').first().val();
var color = $(item).find('input.txtColor').first().val();
addColor(color);
addSize(size);
var _color;
var _size;
$.ajax({
url: '/admin/Product/GetSize',
data: {
Name: size,
},
async: false,
type: 'get',
dataType: 'json',
success: function (data) {
console.log(data);
_color = data;
},
error: function () {
osm.notify('Has an error', 'error');
}
});
$.ajax({
url: '/admin/Product/GetColor',
data: {
Name: color,
},
type: 'get',
async: false,
dataType: 'json',
success: function (data) {
console.log(data);
_size = data;
},
error: function () {
osm.notify('Has an error', 'error');
}
});
quantityList.push({
Id: $(item).data('id'),
ProductId: $('#hidId').val(),
Quantity: $(item).find('input.txtQuantity').first().val(),
SizeId: _size.Id,
ColorId: _color.Id,
});
});
$.ajax({
url: '/admin/Product/SaveQuantities',
data: {
productId: $('#hidId').val(),
quantities: quantityList
},
async: false,
type: 'post',
dataType: 'json',
success: function (response) {
$('#modal-quantity-management').modal('hide');
$('#table-quantity-content').html('');
}
});
});
function addColor(color) {
$.ajax({
url: '/admin/Product/AddColor',
data: {
Name: color,
},
type: 'post',
dataType: 'json',
error: function () {
osm.notify('Has an error', 'error');
}
});
}
function addSize(size) {
$.ajax({
url: '/admin/Product/AddSize',
data: {
Name: size,
},
type: 'post',
dataType: 'json',
error: function () {
osm.notify('Has an error', 'error');
}
});
}
I expect that database already had recognized colorId and sizeId before I add a new quantity but actually it does not.

ASP.NET and jQuery Remote Validation: Validation function not called

I have this client function:
$(document).ready(function() {
var validate = $("#<%=Page.Form.ClientID%>").validate({
errorElement: 'span',
rules: {
<%=txtMemberShipNumber.ClientID %> : {
required: true,
remote: function () {
return {
url: "/TestForm.aspx/IsMembershipNumberValid",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ value: $('#<%=txtMemberShipNumber.ClientID %>').val() }),
dataFilter: function (data) {
var msg = JSON.parse(data);
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
}
},
},
},
messages: {
<%=txtMemberShipNumber.ClientID %> : {
required: "Account number is Required",
remote: "Invalid",
},
},
onkeyup:false,
onblur: true,
onfocusout: function (element) { $(element).valid() }
});
})
... that validates this control:
<input name="ctl00$MainContent$txtMemberShipNumber" type="text" id="MainContent_txtMemberShipNumber" class="textboxStyle" placeholder="Membership Number" />
The problem is the validation code is never called. I've tested it in Firefox and Chrome.
Am I missing something?
I figured it out.
Instead of
<%=txtMemberShipNumber.ClientID %> : {
... you should use
<%=txtMemberShipNumber.UniqueID%> : {

Unable to redirect to another page using javascript while using jquery

I am unable to redirect to another after successful login through my webservice. I am getting correct response from web service But page doesn't redirect.
<script type="text/javascript">
function registerUser() {
try {
var username = document.getElementById("UserName");
var pwd = document.getElementById("Password");
$.ajax({
datatype: "json",
type: "POST",
url: "http://localhost:51290/CMSWebService.asmx/LoginUser",
data: "{'username':'" + username.value + "','pwd':'" + pwd.value + "'}",
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("hello");
window.location.replace("default.aspx");// to redirect error occurs here
},
error: function (data) {
debugger;
if (data.d) {
}
}
});
}
catch (e) {
debugger;
alert(e);
}
}
</script>
Why don't you try window.location.replace(" full url of your page ") .
<script type="text/javascript">
function registerUser() {
try {
var username = document.getElementById("UserName");
var pwd = document.getElementById("Password");
$.ajax({
datatype: "json",
type: "POST",
url: "http://localhost:51290/CMSWebService.asmx/LoginUser",
data: "{'username':'" + username.value + "','pwd':'" + pwd.value + "'}",
async:false,
contentType: "application/json; charset=utf-8",
success: function (data) {
window.location = "./default.aspx";
alert("hello");
},
error: function (data) {
debugger;
if (data.d) {
}
}
});
}
catch (e) {
debugger;
alert(e);
}
}
</script>
Try this

Call a web method using jQuery Ajax

I want to create an Autocomplete field for a search option. I have tried with following code.
But the web method doesn't fire when the Autocomplete function is execution.
What will be the reason ?
Here is the jQuery function:
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
$.ajax ({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
Here is the web method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}
Make sure you hit the webservice function by having breakpoint on your service function. Please change your script to below:
<script type="text/javascript">
$(function () {
$("#<%=tags.ClientID %>").autocomplete
({
source:
function (request, response) {
$.ajax
({
url: " <%=ResolveUrl("~/Services/AutoComplete.asmx/GetFarmersByName") %>",
data: "{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
async: true,
dataFilter: function (data) { return data; },
success: function (data)
{
response($(data.d, function (item)
{
return
{
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
</script>
Above your service class add [System.Web.Script.Services.ScriptService]
Or you can do this in an asp.net page!
add the static keyword and change the webservice to ASP.NET page!
public static string GetFarmersByName(string name)
For example:
A.aspx:
$.ajax({
type: "POST",
url: "A.aspx/GetSN",
data: {},
contentType: "application/json;charset=utf-8",
dataType: "json",
async:false,
success: function (json) {
var msg = JSON.parse(json.d);
sn = msg;
},
failure: function () {
alert("Sorry,there is a error!");
}
});
Then in your A.aspx.cs type in:
[WebMethod]
public static string GetSN()
{
Random RN = new Random();
string year = DateTime.Now.ToString("yy").ToString();
string MonAndDate = DateTime.Now.ToString("MMdd").ToString();
string Hour = DateTime.Now.ToString("HHMMss").ToString() + DateTime.Now.Millisecond.ToString() + RN.Next(100, 900).ToString();
string SerialNumber = year + MonAndDate + Hour;
return JsonConvert.SerializeObject(SerialNumber);
}
Assuming tags as your textbox, set data as { 'name': '" + request.term + "'}
$("#<%=tags.ClientID %>").autocomplete({
source: function (request, response) {
$.ajax({
url: "Services/AutoComplete.asmx/GetFarmersByName",
data: "{ 'name': '" + 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);
},
});
},
minLength: 0,
focus: function () {
// prevent value inserted on focus
return false;
},
});
debug on method GetFarmersByName,
NOTE: Check have you uncomment [System.Web.Script.Services.ScriptService] on .asmx page.
Post again!!!
Test.aspx:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.0.min.js"></script>
<script type="text/javascript">
$(function(){
$("#Button1").bind("click",function(){
$.ajax({
type: "POST",
url: "Test.asmx/GetFarmersByName",
data:"{'aaa':'zhangsan'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
async: false,
success: function (json) {
},
failure: function () {
alert("Sorry,there is a error!");
}
});
})
})
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<input id="Button1" type="button" value="button" />
</div>
</form>
</body>
</html>
Test.asmx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Script.Services;
using System.Web.Services;
namespace TestWebForm
{
/// <summary>
/// Summary description for Test
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Test : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}
}
}
Paste this method inside code behind file where you are calling this method. Change url to url: "Test.aspx/GetFarmersByName" and then test it. Its much clean code rather then Web Service.
using System.Web.Script.Services;
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public List<string> GetFarmersByName(string aaa)
{
List<string> list = new List<string>();
list.Add(aaa);
return list;
}
try this -
<script type="text/javascript">
$(function () { $("#<%=tags.ClientID %>").autocomplete({
source:function (request, response) {
var obj = JSON.Stringfy("{ 'name' : '" + $("#<%=tags.ClientID %>").val() + "'}");
$.ajax ({
type: "POST",
url: "~/Services/AutoComplete.asmx/GetFarmersByName",
data: obj,
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
dataFilter: function (data) { return data; },
success: function (data) {
response($(data.d, function (item) {
return {
value: item.AdrNm
}
}));
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
});
}
});
});
and the webmethod-
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public List<FMISPersonalDataViewByName_Result> GetFarmersByName(string name)
{
this._personalData = new personalData();
int cky = 45;
CdMa cdMas = new CdMa();
cdMas = this._personalData.getcdMasByConcdCd2(cky, "AdrPreFix", true);
int prefixKy = cdMas.CdKy;
List<FMISPersonalDataViewByName_Result> list = new List<FMISPersonalDataViewByName_Result>();
list = this._personalData.GetPersonalDataByName(prefixKy, cky, name);
return list;
}

webservice return bool, using ajax

I got a jQuery prompt that is a password validation. I use a ajax webservice for this task. now my confusion is how should I handle the ajax call and make function bool?
I started with ajax and webservices about a 2 hours ago so be nice.
$(document).ready(function() {
$("#sayHelloButton").click(function() {
jPrompt('Password:', 'Password', 'Password', function(r) {
if (CheckPassword(r) == true) window.location = "http://www.asp.net";
else alert('Wrong password');
});
});
});
function CheckPassword(psw) {
$.ajax({
type: "POST",
url: "dummywebservice.asmx/CheckPassword",
data: "{'" + $('#name').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json"
});
}
webservice
[WebMethod]
public bool CheckPassword(string password)
{
if(!string.IsNullOrEmpty(password))
{
if (password == "testpassword")
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
Change your CheckPassword function to take true and false callbacks like so:
function CheckPassword(psw, ifTrue, ifFalse) {
$.ajax({
type: "POST",
url: "dummywebservice.asmx/CheckPassword",
data: "{'" + $('#name').val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data, textStatus, XMLHttpRequest) {
if (data)
ifTrue();
else
ifFalse();
}
});
}
And then invoke the function like so:
$(document).ready(function() {
$("#sayHelloButton").click(function() {
jPrompt('Password:', 'Password', 'Password', function(r) {
CheckPassword(r,
function ifTrue() {
window.location = "http://www.asp.net";
},
function ifFalse() {
alert('Wrong password');
}
);
});

Resources