简体   繁体   中英

Why does my button click execute multiple times?

I have written this ajax code to send data to web service asmx. It works but with a single click, it inserts data multiple times and sometimes it takes 2,3 click to insert data.

.js

 <script type="text/javascript">

            function save()
            {
                $("button").click
                (
                     function()
                     {
                        $.post
                        (
                            "http://localhost:82/ws/himher.asmx/InsertUsers",
                            {name: txtUserName.value, pwd: txtUserPwd.value},
//                          
                        );

                     }
                );
            }



        </script>
    </head>
<body> 
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">
                 <label>User Name</label>
                 <input id="txtUserName" type="text" class="form-control" />
            </div>
        </div>
        <div class="row">
            <div class="col-md-12">
                 <label>Password</label>
                 <input id="txtUserPwd" type="text" class="form-control" />
            </div>
        </div>    
        <br/>
         <div class="row">
            <div class="col-md-12">     
                 <button type="submit" onclick='save()' class="btn btn-primary pull-right">Register</button>
            </div>
        </div>    
    </div>

.cs:

public class himher : System.Web.Services.WebService
{

    [WebMethod(EnableSession = true)]
    //[ScriptMethod(UseHttpGet = false)]
    public string InsertUsers(string name, string pwd)
    {
        try
        {
            basicoperation bop = new basicoperation();
            return bop.insertUsers(name, pwd);
        }
        catch (Exception ex)
        {

            throw ex;
        }


    }


    public string insertUsers(string Name, string Password)
    {
            string status;

            String ConStr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;

            SqlConnection sqlCon = new SqlConnection(ConStr);    // to make a connection with DB 

            SqlCommand sqlCom = new SqlCommand("InsertUsers", sqlCon); // now in order to perform action such as insert SP, we must create command object which needs command name and conncetion only

            sqlCom.CommandType = CommandType.StoredProcedure;  // you must tell the system that insertInfo is a storedprocedure 

            SqlParameter sqlParamName = new SqlParameter("@UserName", Name);
            SqlParameter sqlParamPwd= new SqlParameter("@Password", Password);

            sqlCom.Parameters.Add(sqlParamName);
            sqlCom.Parameters.Add(sqlParamPwd);      

            try
            {
                sqlCon.Open();

               int i= sqlCom.ExecuteNonQuery();   // executenonquery is used for INSERT, UPDATE, DELETE 

                //sqlCom.ExecuteScalar();   // used to pick or read a single value from procedure
               // Response.Write("Done");

                sqlCon.Close();

                status= "Success";
            }
            catch (Exception ex)
            {
                //response.Write(ex.Message);
                status = ex.Message;
            }
        return status;
    }
}

You have two bindings to a saving function, one of them is binded when you click on your button. Rewrite your JS like this:

<script type="text/javascript">
    function save()
    {
        $.post(
            "http://localhost:82/ws/himher.asmx/InsertUsers",
            {name: txtUserName.value, pwd: txtUserPwd.value}
        );
    }
</script>

This way your save function will do only saving logic. Binding to call this function is done in HTML by <button type="submit" onclick='save()'> .

If you're going to release this code to users you really need to implement some duplicate action prevention rather than hope they just click it once. Ergo while you may find out why it insets multiples, you cannot rely on user behaviour to keep trash out of the database; they will hit a go slow and hammer that button in frustration. Even if you disable the button, they'll refresh and submit again. Dedupe your data before you insert - this is multi layer information security; even if they disable the script that stops them hammering the button, you don't accept the duplicates

Note, I don't offer this as a solution to a genuine "I click this once and 3 data are inserted" - fix that bug sure, but control the user behaviour with regards to your desire for data purity, within the server (where you're in total control)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM