Link to home
Start Free TrialLog in
Avatar of sivakugan
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/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");


        }
    }

   


}
Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

Quick comment....

IsPostBack!=null

is always going to be true, since IsPostBack is either true or false, neither of which is null.
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?
Avatar of sivakugan
sivakugan

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

            }
        }
    }
}
I tried, its not working at all. I really confused now to solve this issue.
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
SubmitButton_Click can only happen on a postback anyway.
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
DID u change this ???


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


});
VERY STRANGE IF U R RETURNING FALSE WHY SERVER SIDE POST BACK EVENT CALLING
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.
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.
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.
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?
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!
Could u plz provide an example?..I created an object and it didn't work out.
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.
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)


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

u mean creating that function in my code behind file?
ASKER CERTIFIED SOLUTION
Avatar of Jens Fiederer
Jens Fiederer
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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.
Brilliant.
My pleasure, good luck with your project.