Check UserName availability by using AJAX in asp.net - asp.net

I'm creating a SignUp form,i want to add a feature to the form in which whenever a new user types an username in the text box, it should automatically check if the username is already taken or not(should compare it with usernames exist in SQL server database). I want to implement this feature using AJAX.

Use the following jquery code, don't forget include jquery libraries
$("#<%=txtJournalIdToMove.ClientID %>").blur(function () {
var journalTextBoxId = '<%= this.txtJournalIdToMove.ClientID %>';
var journalId = $("#" + journalTextBoxId).val();
var params = '{"JournalId":"' + journalId + '"}';
$.ajax({
type: "POST",
url: "Default.aspx/PopulateVolumeNo",
data: params,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
// Replace the div's content with the page method's return.
var returnValue = data.d;
if (returnValue == null) {
alert("The given journal id does not exist or is in active in db.");
}
else {
//If success do your functionality
});
}
}
});
});

Try this onchange or on blur event of a textbox. Here I used user-name-box as text box id
$.post('/Server/CheckAvailablity/',
{name:function(){return $('#user-name-box').val()},
function(response){
if(response.status="Y"){
alert('available');
}
else{
alert('not available');
}
}
);
In server side CheckAvailablity method prepare a JSON object like {"status":"Y"} and return

Related

Set the returned data to Kendo Dropdownlist

I am working in ASP.Net MVC. I have a dropdownlist of Kendo and a form to insert data to database and set the recently inserted data to be selected on kendo dropdown.I am using angular for post method.
var response = $http({
method: "post",
url: loadAllProductsUrl,
data: JSON.stringify(customerdetail),
dataType: "json",
async: false
});
$('#customerModal').modal('hide');
return response.then(function (data) {
if (data != null) {
$("#customers").data("kendoDropDownList").dataSource.read();
setToDropdown(data);
}
else {
}
});
This is my Post method and from here I return the Customer Code and set it to the kendo dropdownlist.
function setToDropdown(data) {
var temp = $("#customers").data("kendoDropDownList");
temp.select(function (dataItem) {
return dataItem.CustomerCode === data;
});
}
But the data is not being set to the dropdownlist because setToDropdown(data) is executed before $("#customers").data("kendoDropDownList").dataSource.read(); is loaded fully. Please suggest....
this helped me
getCustomer(function (a) {
setTimeout(function () {
$("#customers").data("kendoDropDownList").value(data.CustomerName);
}, 100);
});

Html or Aspnet button on ColorBox Popup Redirect to another aspx page on button click

I am stuck with a critical issue.Can some one please suggest.
I have an .ascx page on which there is a pop up which has an aspnet button which must redirect to another page on click.
I followed the following steps:
On ascx page after opening colorbox, this function is called on clicking the button.
$.ajax({
type: 'POST',
url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
contentType: 'application/json;charset=utf-8',
dataType: 'json',
success: function (response) {
alert(response);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest + textStatus + errorThrown);
}
});
On aspx page
[WebMethod]
public static void btnSaveData()
{
function sahil();//this function i want to call after this function is being called
}
I am getting Json parse error.
I removed dataType:json and made it return a html/text then it is giving me object object error.
This would propably be a lot easier if you could use a simple html form, add the value to a hidden input when onsubmit is triggered, and post it to a webservice which will redirect for you.
Anyway:
You need to decorate your btnSaveData method with another attribute and change the return type / parameter to string (or any other type that suits your needs):
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod]
public static string btnSaveData(string color)
{
// do sth with the color
return "/SaveSuccess.aspx";
}
And in js:
// retrieve the color as a string (this is up to you - I don't know what sort of ColorPicker you're using, so this is a placeholder)
function saveColor()
{
var color = $('#myColorPicker').color.toString();
// create the data for the webmethod,
// the parameternames have to be the same as they are on the WebMethod
var colorData = "{ color:'" + color + "'}";
$.ajax({
type: 'POST',
url: "/HomeLoan/ProductConfirmationPop_SaveData.aspx/btnSaveData",
contentType: 'application/json;charset=utf-8',
dataType: 'json',
data: colorData,
success: function (response) {
window.location.href = response.d; // redirect on success
},
error: function (response, text, error)
{
alert(response + ' ' + text + ' ' + error);
}
});
Hope this helps and works!

ASP.NET Validate membership email from ClientSideEvents and WebMethod

I have ASPxGridview and i want to check if email already registered before or not in editform using ClientSideEvents.
Any help to resolve this problem ?
aspx section
this is the javascript section
function OnEmailValidation(s, e) {
var error = "";
var tfld = trim(e.value);
var illegalChars = /^\w+([-+.'''']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
if (!illegalChars.test(tfld)) {
$get("spanEmail").innerHTML = "invalid email";
} else {
PageMethods.CheckEmail(e.value.toString(), OnCheckEmail);
// how to check OnCheckEmail before continue
//if(email already registered) {
// return false
//}
$get("spanEmail").innerHTML = "";
}
return true;
}
function OnCheckEmail(unavailable) {
if (unavailable == true) {
$get("spanEmail").innerHTML = "already registered";
$get("spanEmail").style.color = "red";
}
else if (unavailable != true) {
$get("spanEmail").innerHTML = "Available";
$get("spanEmail").style.color = "#76EB69";
}
}
aspx.cs
col_Email.PropertiesTextEdit.ClientSideEvents.Validation = "OnEmailValidation";
grid.Columns.Add(col_Email);
[WebMethod]
public static bool CheckEmail(string email)
{
System.Threading.Thread.Sleep(200);
if (Membership.FindUsersByEmail(email) != null)
{
if (Membership.FindUsersByEmail(email).Count <= 0)
{
return false;
}
return true;
}
else
{
return false;
}
}
This is my final code after the
Filip
advice but i have mini problem:
When i use
(async: false) and cntr.SetIsValid(false);
the control doesn't apply the action
but If i use
(async: true) and cntr.SetIsValid(false);
the control apply the action
Why ?
I want to use async: false
function OnEmailValidation(s, e) {
var illegalChars = /^\w+([-+.'''']\w+)*#\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
var spanEmail = document.getElementById("spanEmail");
var obj = GetObj('txt_Email');
var cntr = aspxGetControlCollection().Get(obj.id);
if (!illegalChars.test(e.value)) {
spanEmail.innerHTML = "Invalid Email";
spanEmail.style.color = "red";
cntr.SetIsValid(false);
} else {
$.ajax({
type: "POST",
async: false,
url: "myweb_service.asmx/CheckEmail",
data: "{'email':'" + e.value.toString() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
if (res.d == "true") {
spanEmail.innerHTML = "Email register before";
spanEmail.style.color = "red";
cntr.SetIsValid(false);
}
if (res.d == "false") {
spanEmail.innerHTML = "Available";
spanEmail.style.color = "#76EB69";
cntr.SetIsValid(true);
}
}
});
}}
You can use jQuery to call PageMethods (replace PageMethods.CheckEmail call with this code):
$.ajax({
type: "POST",
async: false,
url: "<PageName>.aspx/CheckEmail",
data: "{" + e.value.toString() + "}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(res) {
if (res.d)
return false;
}
});
Replace PageName with your page name.
Be careful with synchronous (async: false) ajax calls. They will block your page until request finishes.
If res.d doesn't return result or you just want detailed explanation of posted code check these links:
Using jQuery to directly call aspnet ajax page methods
A breaking change between versions of aspnet ajax
You will need to set up a web service on the server side that will check if the email already exists. Then you will use JavaScript AJAX (preferably a library like jQuery or Prototype) to query the web service during your validation method.
it will be a good deal of work to get it all set up. Good luck. See one of these links for more information:
http://msdn.microsoft.com/en-us/library/bb532367.aspx
http://msdn.microsoft.com/en-us/library/t745kdsh.aspx

Message from webpage undefined

I am returning a simple string from a webmethod to a Javascript function.
I am using an AJAX enabled website in ASP.NET 2.0. I get the date in firefox but inside IE 8 it returns undefined.
Do I have to parse the string in the JSON format using some serialize class? In my webmethod, I am just using:
return DateTime.Now.ToString();
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
$.ajax({
type: "POST",
url : pageUrl+ '/getDet',
data : '{categ: "' +trgId + '"}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success:OnSuccess,
failure: function(msg){
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert('error fetching values from database');
}
});
});
function OnSuccess(msg)
{
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
alert(msg);
}
});
Edit
It seems the success function is firing the problem is with response 'alert(msg)' works in firefox but not in IE 8 with asp.net 2.0
Maybe you dont want to use this, but I´m very happy with the asp net ajax build in function, since it builds a header, that works properly on browsers.
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=trgNo.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
var proxy = Sys.Net.WebServiceProxy;
proxy.invoke("", // if current page "", if webservice "/srv.asmx"
"getDet", //method name
false, //post = true, get = false
{ categ : trgId }, //javascript object
OnSuccess, // Success Function
onError, // Error Function
{ yourOwn : userData } // Custom User Data to Handler
);
});
function OnSuccess(response, usercontext)
{
// usercontext.yourOwn === userData;
// response is sent WITHOUT "d", it is removed internally by the proxy
alert(response);
}
});
Dont forget to include the ScriptManager...

Adding JSON results to a drop down list with JQUERY

I'm making a call to a page method via AJAX in my ASP.NET application via JQUERY's AJAX method e.g.
$.ajax({
type: "POST",
url: "page.aspx/GetDropDowns",
data: "{'aId':'1'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg.d);
},
error: function() {
alert('Error getting page');
}
I'll be returning the results in JSON format, whereby I will be populating a drop down. I could do this part myself but I want to know if there is any built in magic in JQuery for processing JSON results or if there are any good utility scripts for this sort of thing.
There is little jQuery itself can help you with populating dropdown. You just need to create HTML and append it to your dropdown.
I'm not sure what is the format of your data so I'm assuming it's an object where keys should be dropdown's keys and values should be dropdown's values.
I also prefer using $.post then $.ajax as it has a clearer structure for me.
$.post('page.aspx/GetDropDowns', {'aId': '1'}, function (data, status) {
if (status === 'success') {
var options = [];
for (var key in data) {
options.push('<option value="' + key + '">' + data[key] + '</option>');
}
$('#yourId').append(options.join(''));
} else {
alert('error');
}
}, 'json');
In the past I have used a plugin when working with dropdowns.
http://www.texotela.co.uk/code/jquery/select
Request the JSON data:
//Get the JSON Data
$.getJSON(url, function(json) {
PopulateDropDownFromJson(json, "#element");
});
and then just pass the JSON into a function that uses the plugin above
function PopulateDropDownFromJson(json, element){
$.each(json, function() {
$(element).addOption(this[valueText], this[displayText], false);
});
}

Resources