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%> : {
Related
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.
I have a kendo grid with 4 checkbox columns with checked and unchecked status.
Now I want to updated tabel based on checkbox checked status on custom command button click.
Here is my kendo grid binding code
$(document).ready((function () {
$.ajax({
type: "POST",
url: "member-security-list.aspx/getStatus",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
$("#grid").kendoGrid({
dataSource: {data: response.d,pageSize: 20},
sortable: {mode: "single",allowUnsort: false},
pageable: {buttonCount: 5},
scrollable: false,
columns: [
{ field: "login", title: "Login Id" },
{ field: "name", title: "Member Name" },
{ field: "mobile", title: "Mobile No." },
{ field: "Alert Status", template: "<input type='checkbox' value='oncredit' class='oncredit' #if(oncredit === '1'){#= checked='checked' #}else{}#= />On Credit <input type='checkbox' value='ondebit' class='ondebit' #if(ondebit === '1'){#= checked='checked' #}else{}#= />On Debit <input type='checkbox' value='onlogin' class='onlogin' #if(onlogin === '1'){#= checked='checked' #}else{}#= />On Login <input type='checkbox' value='isblock' class='isblock' #if(isblock === '1'){#= checked='checked' #}else{}#= />Block SMS Recharge" },
{ command: { text: "Set", click: showDetails }, title: "Set" }
]
});
},
failure: function (response) {
alert(response.d);
}
});
}));
and here is my command button click code
function showDetails(e) {
e.preventDefault();
var d = this.dataItem($(e.currentTarget).closest("tr"));
//I want to access checkbox here and find its checked status for pass parameter.
$.ajax({
type: "POST", url: "member-security-list.aspx/setAlert",
data: '{ "id":"' + d.id + '","status":"' + d.status + '"}',
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
//some other
},
failure: function (response) { }
});
}
Now I have solved my problem. Here is my working code
function showDetails(e) {
e.preventDefault();
var credit, debit, login, block;
var d = this.dataItem($(e.currentTarget).closest("tr"));
var tr = $(e.target).closest("tr");
if (tr.find('.oncredit').is(':checked'))
credit = '1';
else
credit = '0';
if (tr.find('.ondebit').is(':checked'))
debit = '1'
else
debit = '0';
if (tr.find('.onlogin').is(':checked'))
login = '1';
else
login = '0';
if (tr.find('.isblock').is(':checked'))
block = '1'
else
block = '0';
$.ajax({
type: "POST", url: "member-security-list.aspx/setAlert",
data: '{ "id":"' + d.id + '","oncredit":"' + credit + '","ondebit":"' + debit + '","onlogin":"' + login + '","isblock":"' + block + '"}',
contentType: "application/json; charset=utf-8", dataType: "json",
success: function (response) {
alert('Updated');
},
failure: function (response) { }
});
}
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 %>', '');
},
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;
}
my target is to create form that validated in the client side, and only when it is valid, send ajax call to asmx web service. i manage to do that two separately: client-side validation and ajax send to web service, and i want to combine this two. how?..
i have this form (i simplify everything for simple example):
<form id="ContactForm" runat="server">
<label for="name">Full Name</label>
<input type="text" name="name" id="name"/>
<input id="submit" type="button" />
</form>
the client validation looks like:
$(document).ready(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName }
}).form();
});
});
and the ajax send looks like this:
$(document).ready(function() {
$("#submit").click(function() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax
({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
AjaxSucceeded(msg);
}, error: AjaxFailed
});
});
});
Thanks!
You can use the submitHandler option of .valdiate() for this, it only executes when a valid form is submitted (it has an invalidHandler for the opposite), like this:
$(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName },
submitHandler: function() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
}).form();
});
});
Since you're not using this though, it might be much more readable in 2 functions, like this:
$(function() {
$("#submit").click(function() {
var validator = $("#ContactForm").validate({
rules: { name: { required: true } },
messages: { name: errName },
submitHandler: ajaxSubmit
}).form();
});
function ajaxSubmit() {
var myMailerRequest = {name: $('#name').val()};
var data = JSON.stringify({req: myMailerRequest});
$.ajax({
type: "POST",
url: "ContactFormMailer.asmx/SendContactForm",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
}
});
The only other change was shortening your call to AjaxSuceeded (maybe this can't be done, only because of your simplified example), but other than that...just submit the form from the submitHandler callback and you're all set.