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/CheckUserNameAvailability',
                       data: '{userName: \'' + userNameTextBox.val() + '\'}',
                       contentType: 'application/json; charset=utf-8',
                       dataType: 'json',
                       success: OnCheckUserNameAvailabilitySuccess,
                       error: OnCheckUserNameAvailabilityError
                   });
               }
               return false; //Prevent postback
           });

           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);

                           break;
                       case 1:
                           userNameAvailabilityLabel
                            .removeClass()
                            .addClass('used')
                            .html(usedUserNameMessage);
                           break;
                   }
               }
           }
           function OnCheckUserNameAvailabilityError(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 OnCheckUserNameAvailabilitySuccess()
    {
        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)
        {

                OnCheckUserNameAvailabilitySuccess();
           
                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");


        }
    }

   


}
sivakuganAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jens FiedererTest Developer/ValidatorCommented:
Quick comment....

IsPostBack!=null

is always going to be true, since IsPostBack is either true or false, neither of which is null.
0
Jens FiedererTest Developer/ValidatorCommented:
In your code behind, you handle submit by calling OnCheckUserNameAvailabilitySuccess, 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?
0
sivakuganAuthor Commented:
Can you provide sample coding for that?
0
Ultimate Tool Kit for Technology Solution Provider

Broken down into practical pointers and step-by-step instructions, the IT Service Excellence Tool Kit delivers expert advice for technology solution providers. Get your free copy now.

Jens FiedererTest Developer/ValidatorCommented:
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.
0
khan_webguruCommented:
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


 
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
           }

Open in new window


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
0
sivakuganAuthor Commented:
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.
0
khan_webguruCommented:
Is page posting back means refresh or just AJAX call played???

Regards,

Asif Ahmed Khan
0
khan_webguruCommented:
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
0
sivakuganAuthor Commented:
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(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 Sample : System.Web.Services.WebService
{

    [WebMethod]
    public int CheckUserNameAvailability(string userName)
    {
        string connectionString =
        "Data Source=YourServerName; Initial Catalog=YourDatabase; User ID=YourUserName; Password=YourPassword";
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            using (SqlCommand command = new SqlCommand())
            {
                command.Connection = connection;
                command.CommandText = "CheckUserNameAvailability";
                command.CommandType = CommandType.StoredProcedure;

                SqlParameter paramUserName = new SqlParameter("@UserName", SqlDbType.VarChar, 30);
                paramUserName.Value = userName;
                command.Parameters.Add(paramUserName);

                connection.Open();

                int result = Int32.Parse((command.ExecuteScalar().ToString()));

                return result;

            }
        }
    }
}
0
sivakuganAuthor Commented:
I tried, its not working at all. I really confused now to solve this issue.
0
sivakuganAuthor Commented:
Any solution guyes..plz help me?
0
khan_webguruCommented:
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
0
Jens FiedererTest Developer/ValidatorCommented:
SubmitButton_Click can only happen on a postback anyway.
0
sivakuganAuthor Commented:
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
0
khan_webguruCommented:
DID u change this ???


data: '{userName: \'' + userNameTextBox.val() + '\'}',

why you are setting back slashes removed that

data: '{userName: ' + userNameTextBox.val() + '}',
0
khan_webguruCommented:
BRO!

Also change this

 $(function () {


)};

to following:

$(document).ready(function() {

  // all your code on load should be there


});
0
khan_webguruCommented:
VERY STRANGE IF U R RETURNING FALSE WHY SERVER SIDE POST BACK EVENT CALLING
0
sivakuganAuthor Commented:
Thanks Bro for helping but it didn't work. out.
0
Jens FiedererTest Developer/ValidatorCommented:
So in my previous example, instead of using Customers.Exists(username) you can call your web method.
0
sivakuganAuthor Commented:
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.
0
Jens FiedererTest Developer/ValidatorCommented:
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.
0
sivakuganAuthor Commented:
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?
0
Jens FiedererTest Developer/ValidatorCommented:
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!
0
sivakuganAuthor Commented:
Could u plz provide an example?..I created an object and it didn't work out.
0
sivakuganAuthor Commented:
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.
0
Jens FiedererTest Developer/ValidatorCommented:
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)


)
0
Jens FiedererTest Developer/ValidatorCommented:
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.CheckUserNameAvailability(username) == 1) {

etc.

0
sivakuganAuthor Commented:
u mean creating that function in my code behind file?
0
Jens FiedererTest Developer/ValidatorCommented:
either in the code behind file or a separate class in the project with the code behind.

If you're doing just one, you could put it right in the code behind, but in a larger project it is best to organize things.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
sivakuganAuthor Commented:
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.
0
sivakuganAuthor Commented:
Brilliant.
0
Jens FiedererTest Developer/ValidatorCommented:
My pleasure, good luck with your project.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
ASP.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.