sivakugan
asked on
How to stop the function when its finished its task
Hi,
I have developed to check the username availability in registration form. It is functioning very well
when you click the "Check availability" button. But when you click the submit button with the username that is already existing in the db, it is saying the username is already existing but it is inserting the records into db. I don't want to insert the records when the username is already existing.
Here is the code in head tag
-------------------------- ---------- ----------
<script type="text/javascript">
var emptyUserNameMessage = 'Please enter the username';
var progressUserNameMessage = 'Checking...';
var availableUserNameMessage = 'Username is available';
var usedUserNameMessage = 'Username has been taken';
$(function () {
var userNameAvailabilityLabel = $('#<%= UserNameAvailabilityLabel. ClientID %>');
$('#<%= UserNameAvailabilityButton .ClientID %>').click(function () {
var userNameTextBox = $('#<%= UserNameTextBox.ClientID %>');
var userName = userNameTextBox.val();
if ($.trim(userName) == '') {
userNameAvailabilityLabel
.removeClass()
.addClass('required')
.html(emptyUserNameMessage );
}
else {
userNameAvailabilityLabel. html('');
$('#ProgressDiv').show();
$.ajax({
type: 'POST',
url: 'Sample.asmx/CheckUserName Availabili ty',
data: '{userName: \'' + userNameTextBox.val() + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: OnCheckUserNameAvailabilit ySuccess,
error: OnCheckUserNameAvailabilit yError
});
}
return false; //Prevent postback
});
function OnCheckUserNameAvailabilit ySuccess(r esponse) {
$('#ProgressDiv').hide();
if (response != null && response.d != null) {
var data = response.d;
switch (data) {
case 0:
userNameAvailabilityLabel
.removeClass()
.addClass('available')
.html(availableUserNameMes sage);
break;
case 1:
userNameAvailabilityLabel
.removeClass()
.addClass('used')
.html(usedUserNameMessage) ;
break;
}
}
}
function OnCheckUserNameAvailabilit yError(xhr , ajaxOptions, thrownError) {
alert(xhr.statusText);
}
});
</script>
Here is the code in code behind file
-------------------------- ---------- ---------- -----
using System;
using System.Collections.Generic ;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void OnCheckUserNameAvailabilit ySuccess()
{
Response.Write("Username is already taken");
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
Customers com = new Customers();
int CustomerID=0;
string Username = UserNameTextBox.Text;
string passwords = PasswordTextBox.Text;
string repasswords = RetypePasswordTextBox.Text ;
string firstname = FirstnameTextBox.Text;
string lastname = LastnameTextBox.Text;
string Address1 = Address1TextBox.Text;
string Address2 = Address2TextBox.Text;
string PostalCode = PostalCodeTextBox.Text;
string Customermail = EmailTextBox.Text;
string Phone = ContactNoTextBox.Text;
if (IsPostBack!=null)
{
OnCheckUserNameAvailabilit ySuccess() ;
Customers.InsertCustomers( CustomerID , Username, passwords, firstname, lastname, Address1, Address2, PostalCode, Customermail, Phone);
Response.Write("You have registered successfully");
UserNameTextBox.Text = "";
PasswordTextBox.Text = "";
RetypePasswordTextBox.Text = "";
FirstnameTextBox.Text = "";
LastnameTextBox.Text = "";
Address1TextBox.Text = "";
Address2TextBox.Text = "";
PostalCodeTextBox.Text = "";
EmailTextBox.Text = "";
ContactNoTextBox.Text = "";
}
else
{
Response.StatusCode = 404;
this.Visible = false;
Response.Write("404 Page Not Found");
}
}
}
I have developed to check the username availability in registration form. It is functioning very well
when you click the "Check availability" button. But when you click the submit button with the username that is already existing in the db, it is saying the username is already existing but it is inserting the records into db. I don't want to insert the records when the username is already existing.
Here is the code in head tag
--------------------------
<script type="text/javascript">
var emptyUserNameMessage = 'Please enter the username';
var progressUserNameMessage = 'Checking...';
var availableUserNameMessage = 'Username is available';
var usedUserNameMessage = 'Username has been taken';
$(function () {
var userNameAvailabilityLabel = $('#<%= UserNameAvailabilityLabel.
$('#<%= UserNameAvailabilityButton
var userNameTextBox = $('#<%= UserNameTextBox.ClientID %>');
var userName = userNameTextBox.val();
if ($.trim(userName) == '') {
userNameAvailabilityLabel
.removeClass()
.addClass('required')
.html(emptyUserNameMessage
}
else {
userNameAvailabilityLabel.
$('#ProgressDiv').show();
$.ajax({
type: 'POST',
url: 'Sample.asmx/CheckUserName
data: '{userName: \'' + userNameTextBox.val() + '\'}',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: OnCheckUserNameAvailabilit
error: OnCheckUserNameAvailabilit
});
}
return false; //Prevent postback
});
function OnCheckUserNameAvailabilit
$('#ProgressDiv').hide();
if (response != null && response.d != null) {
var data = response.d;
switch (data) {
case 0:
userNameAvailabilityLabel
.removeClass()
.addClass('available')
.html(availableUserNameMes
break;
case 1:
userNameAvailabilityLabel
.removeClass()
.addClass('used')
.html(usedUserNameMessage)
break;
}
}
}
function OnCheckUserNameAvailabilit
alert(xhr.statusText);
}
});
</script>
Here is the code in code behind file
--------------------------
using System;
using System.Collections.Generic
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Registration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void OnCheckUserNameAvailabilit
{
Response.Write("Username is already taken");
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
Customers com = new Customers();
int CustomerID=0;
string Username = UserNameTextBox.Text;
string passwords = PasswordTextBox.Text;
string repasswords = RetypePasswordTextBox.Text
string firstname = FirstnameTextBox.Text;
string lastname = LastnameTextBox.Text;
string Address1 = Address1TextBox.Text;
string Address2 = Address2TextBox.Text;
string PostalCode = PostalCodeTextBox.Text;
string Customermail = EmailTextBox.Text;
string Phone = ContactNoTextBox.Text;
if (IsPostBack!=null)
{
OnCheckUserNameAvailabilit
Customers.InsertCustomers(
Response.Write("You have registered successfully");
UserNameTextBox.Text = "";
PasswordTextBox.Text = "";
RetypePasswordTextBox.Text
FirstnameTextBox.Text = "";
LastnameTextBox.Text = "";
Address1TextBox.Text = "";
Address2TextBox.Text = "";
PostalCodeTextBox.Text = "";
EmailTextBox.Text = "";
ContactNoTextBox.Text = "";
}
else
{
Response.StatusCode = 404;
this.Visible = false;
Response.Write("404 Page Not Found");
}
}
}
In your code behind, you handle submit by calling OnCheckUserNameAvailabilit ySuccess, which prints out an error message every time. Perhaps this should check the database to see if the username already exists instead, and return some kind of status to affect further processing?
ASKER
Can you provide sample coding for that?
Not really, because I don't know the methods of your "Customers" object. Only you know that.
Obviously it has an InsertCustomers method, it might have some methods for checking existing customers as well. It looks like you ALWAYS try to insert a customer ID of "0", I don't know if that is correct.
if Customers has an "Exists" method, for example, you'd want to do:
if (Customers.Exists(username )) {
Response.Clear();
Response.Write("Username is already taken");
} else {
Customers.InsertCustomers( CustomerID , Username, passwords, firstname, lastname, Address1, Address2, PostalCode, Customermail, Phone);
....etc....
}
Note that you never want to mix Response.Write with settings of controls - if you want to send a message back to the user you normally set the text of a label that is used for that purpose. Response.Write is really only if you want to present a page generated ONLY by Response.Writes.
Obviously it has an InsertCustomers method, it might have some methods for checking existing customers as well. It looks like you ALWAYS try to insert a customer ID of "0", I don't know if that is correct.
if Customers has an "Exists" method, for example, you'd want to do:
if (Customers.Exists(username
Response.Clear();
Response.Write("Username is already taken");
} else {
Customers.InsertCustomers(
....etc....
}
Note that you never want to mix Response.Write with settings of controls - if you want to send a message back to the user you normally set the text of a label that is used for that purpose. Response.Write is really only if you want to present a page generated ONLY by Response.Writes.
Hello Bro!
I found the problem please perform following action that will resolve your issue.
Just add return values in both cases in your switch:
like below
I added the return value in above code with "// Added By Khan" comments.
Reasons
You are returning false in your main function to preventing your call back but when ajax response come back from server new function calls that always return true so you have to stop thats post backs.
You have is Available check in JAVASCRIPT but care about in post back too where you are doing some thing like that
Customers.InsertCustomers( CustomerID , Username, passwords, firstname, lastname, Address1, Address2, PostalCode, Customermail, Phone);
Hope you are getting my point. Let me know If you are still facing this issue.
Regards,
Asif Ahmed Khan
I found the problem please perform following action that will resolve your issue.
Just add return values in both cases in your switch:
like below
function OnCheckUserNameAvailabilitySuccess(response) {
$('#ProgressDiv').hide();
if (response != null && response.d != null) {
var data = response.d;
switch (data) {
case 0:
userNameAvailabilityLabel
.removeClass()
.addClass('available')
.html(availableUserNameMessage);
return false; // Added By Khan
break;
case 1:
userNameAvailabilityLabel
.removeClass()
.addClass('used')
.html(usedUserNameMessage);
return false; // Added By Khan
break;
}
}
}
function OnCheckUserNameAvailabilityError(xhr, ajaxOptions, thrownError) {
alert(xhr.statusText);
return false; // Added By Khan
}
I added the return value in above code with "// Added By Khan" comments.
Reasons
You are returning false in your main function to preventing your call back but when ajax response come back from server new function calls that always return true so you have to stop thats post backs.
You have is Available check in JAVASCRIPT but care about in post back too where you are doing some thing like that
Customers.InsertCustomers(
Hope you are getting my point. Let me know If you are still facing this issue.
Regards,
Asif Ahmed Khan
ASKER
I changed it as you advised but still i am getting the same error. I could able to enter the user name that is existing already, through submit button. Which is not good at all.
Is page posting back means refresh or just AJAX call played???
Regards,
Asif Ahmed Khan
Regards,
Asif Ahmed Khan
Bro
Also try one thing
data: '{userName: \'' + userNameTextBox.val() + '\'}',
why you are setting back slashes removed that
data: '{userName: ' + userNameTextBox.val() + '}',
I think the web services you are calling check that if u still have problem then problem is on server side above mentioned back slashes means "\Asif\" this is sending by you on server for compare data base will have "Asif" so it will return 0 might be possible that will be a problem.
Regards,
Asif Ahmed Khan
Also try one thing
data: '{userName: \'' + userNameTextBox.val() + '\'}',
why you are setting back slashes removed that
data: '{userName: ' + userNameTextBox.val() + '}',
I think the web services you are calling check that if u still have problem then problem is on server side above mentioned back slashes means "\Asif\" this is sending by you on server for compare data base will have "Asif" so it will return 0 might be possible that will be a problem.
Regards,
Asif Ahmed Khan
ASKER
I have added one web service too .
Here is the web service code for that
-------------------------- ---------- ---------- ---------
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
/// <summary>
/// Summary description for Sample
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(Conform sTo = WsiProfiles.BasicProfile1_ 1)]
[System.ComponentModel.Too lboxItem(f alse)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Service s.ScriptSe rvice]
public class Sample : System.Web.Services.WebSer vice
{
[WebMethod]
public int CheckUserNameAvailability( string userName)
{
string connectionString =
"Data Source=YourServerName; Initial Catalog=YourDatabase; User ID=YourUserName; Password=YourPassword";
using (SqlConnection connection = new SqlConnection(connectionSt ring))
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "CheckUserNameAvailability ";
command.CommandType = CommandType.StoredProcedur e;
SqlParameter paramUserName = new SqlParameter("@UserName", SqlDbType.VarChar, 30);
paramUserName.Value = userName;
command.Parameters.Add(par amUserName );
connection.Open();
int result = Int32.Parse((command.Execu teScalar() .ToString( )));
return result;
}
}
}
}
Here is the web service code for that
--------------------------
using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Services;
/// <summary>
/// Summary description for Sample
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(Conform
[System.ComponentModel.Too
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Service
public class Sample : System.Web.Services.WebSer
{
[WebMethod]
public int CheckUserNameAvailability(
{
string connectionString =
"Data Source=YourServerName; Initial Catalog=YourDatabase; User ID=YourUserName; Password=YourPassword";
using (SqlConnection connection = new SqlConnection(connectionSt
{
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
command.CommandText = "CheckUserNameAvailability
command.CommandType = CommandType.StoredProcedur
SqlParameter paramUserName = new SqlParameter("@UserName", SqlDbType.VarChar, 30);
paramUserName.Value = userName;
command.Parameters.Add(par
connection.Open();
int result = Int32.Parse((command.Execu
return result;
}
}
}
}
ASKER
I tried, its not working at all. I really confused now to solve this issue.
ASKER
Any solution guyes..plz help me?
Hello Bro!
how can I know what logic u implemented in your SP stored proc :P
any way just break your code here that whats param is going in SP???? is that fine?????
Regards,
AAK
how can I know what logic u implemented in your SP stored proc :P
any way just break your code here that whats param is going in SP???? is that fine?????
Regards,
AAK
SubmitButton_Click can only happen on a postback anyway.
ASKER
Here is the SP
-------------------------- ---
CREATE PROCEDURE [CheckUserNameAvailability ] @UserName VARCHAR(30)
AS
BEGIN
SET NOCOUNT ON
IF EXISTS ( SELECT 1
FROM Users
WHERE UserName = @UserName )
SELECT '1'
ELSE
SELECT '0'
SET NOCOUNT OFF
END
--------------------------
CREATE PROCEDURE [CheckUserNameAvailability
AS
BEGIN
SET NOCOUNT ON
IF EXISTS ( SELECT 1
FROM Users
WHERE UserName = @UserName )
SELECT '1'
ELSE
SELECT '0'
SET NOCOUNT OFF
END
DID u change this ???
data: '{userName: \'' + userNameTextBox.val() + '\'}',
why you are setting back slashes removed that
data: '{userName: ' + userNameTextBox.val() + '}',
data: '{userName: \'' + userNameTextBox.val() + '\'}',
why you are setting back slashes removed that
data: '{userName: ' + userNameTextBox.val() + '}',
BRO!
Also change this
$(function () {
)};
to following:
$(document).ready(function () {
// all your code on load should be there
});
Also change this
$(function () {
)};
to following:
$(document).ready(function
// all your code on load should be there
});
VERY STRANGE IF U R RETURNING FALSE WHY SERVER SIDE POST BACK EVENT CALLING
ASKER
Thanks Bro for helping but it didn't work. out.
So in my previous example, instead of using Customers.Exists(username) you can call your web method.
ASKER
Hello jensfiederer:,
I do not have "Exists" method in my customer class. I have methods for inserting,updating and deleting.
I used SP for that. If you can mention with coding, that would be greatful.
Thanks.
I do not have "Exists" method in my customer class. I have methods for inserting,updating and deleting.
I used SP for that. If you can mention with coding, that would be greatful.
Thanks.
Assuming your web service is available as a regular function (if you need to call it as a web service even on the server side, just bring it in)
if (CheckUserNameAvailability (username) == 1) {
Response.Clear();
Response.Write("Username is already taken");
} else {
Customers.InsertCustomers( CustomerID , Username, passwords, firstname, lastname, Address1, Address2, PostalCode, Customermail, Phone);
....etc....
}
Since your problem is what happens when you hit the submit button, I'm really looking at your SubmitButton_Click - the Ajax part you aren't complaining about.
if (CheckUserNameAvailability
Response.Clear();
Response.Write("Username is already taken");
} else {
Customers.InsertCustomers(
....etc....
}
Since your problem is what happens when you hit the submit button, I'm really looking at your SubmitButton_Click - the Ajax part you aren't complaining about.
ASKER
Yes. I am not having problem in ajax part. I am really having problem in code behind.
I have tried to put the coding as u mentioned but the "CheckUserNameAvailability " is a different data type and when you compare as boolean. Its not recognizing it. it is saying - Cannot convert method group tp non-delegate boolean type.Did you intend to invoke the method?
I have tried to put the coding as u mentioned but the "CheckUserNameAvailability
Yes, I intended to invoke the method - but since it is not a static, I guess I'd need an instance of the web service first, and call the method on that instance.
Easier when it's just a static method!
Easier when it's just a static method!
ASKER
Could u plz provide an example?..I created an object and it didn't work out.
ASKER
Hi jensfiederer,
Thanks for your help. Help me with writing the method for Exist in Customer class. As i am having other methods like insert,update and delete.
then I could call that method in my code behind file in submit button click event as u mentioned earlier.
I think the problem will be solved in this way and I do not need to worry about ajax part.
Thanks for your help. Help me with writing the method for Exist in Customer class. As i am having other methods like insert,update and delete.
then I could call that method in my code behind file in submit button click event as u mentioned earlier.
I think the problem will be solved in this way and I do not need to worry about ajax part.
It's easiest to just create a function in your own project
public static int CheckUserNameAvailability( string userName)
and give it the same body as your web service had, but if you want to call the web service you can right-click on your project, choose "Add Service Reference", browse to your web service and create a reference to that, and then instantiate a reference to the service class as in http://articles.sitepoint.com/article/net-web-services-5-steps/3
( the interesting part here is
Dim supInfo As New WService.GetInfo()
Dim MyData As DataSet = supInfo.ShowSuppliers (Catg)
)
public static int CheckUserNameAvailability(
and give it the same body as your web service had, but if you want to call the web service you can right-click on your project, choose "Add Service Reference", browse to your web service and create a reference to that, and then instantiate a reference to the service class as in http://articles.sitepoint.com/article/net-web-services-5-steps/3
( the interesting part here is
Dim supInfo As New WService.GetInfo()
Dim MyData As DataSet = supInfo.ShowSuppliers (Catg)
)
Ooops, meant the C# code:
GetInfo supInfo = new GetInfo();
DataSet MyData = supInfo.ShowSuppliers(Catg );
(which in your case would be
Sample sample = new Sample();
and later
if (sample.CheckUserNameAvail ability(us ername) == 1) {
etc.
GetInfo supInfo = new GetInfo();
DataSet MyData = supInfo.ShowSuppliers(Catg
(which in your case would be
Sample sample = new Sample();
and later
if (sample.CheckUserNameAvail
etc.
ASKER
u mean creating that function in my code behind file?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Finally it is working..I have created a method in customer class based on web method then called that method in code behind file..Thanks a lot for you...many many thanks.
ASKER
Brilliant.
My pleasure, good luck with your project.
IsPostBack!=null
is always going to be true, since IsPostBack is either true or false, neither of which is null.