in javascript visual studio database programming, i am fashing very unusual behaviour of program execution. i have javascript code like this:
<script type="text/javascript">
function GetValue6(id1, id2, id3) {
var user = {};
user.Username = $("[id*='" + id1 + "']").val();
user.Password = $("[id*='" + id2 + "']").val();
alert(user.Username);
$.ajax({
type: "POST",
url: '<%= ResolveUrl("Default.aspx/SaveUser") %>',
data: '{user: ' + JSON.stringify(user) + '}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert("User has been added successfully.");
window.location.reload();
},
error: function () { alert("There was an error."); }
});
return false;
}
</script>
and code behind file like this:
child.Text = "<input type='text' id='" + TextGUID1 + "' value='" + rows[i]
["Area"].ToString() + "'/>
<input type='text' id='" + TextGUID2 + "' value='" + rows[i]
["Area"].ToString() + "'/>
<input type = 'button' id='" + ButtonGUID3 + "' onclick=\"GetValue6('" +
TextGUID1 + "','" + TextGUID2 + "','" + ButtonGUID3 + "')\" value='Save'
/>
public static void SaveUser(User user)
{
string constr =
ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("INSERT INTO Users2
VALUES(@Username, @Password)"))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@Username", user.Username);
cmd.Parameters.AddWithValue("@Password", user.Password);
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
There is a very strange behaviour that i am facing, when i run above code by clicking "Save" button then i face error alert message "There was an error.". But when i run the program in debugging mode and press F10(Step over new function call) then i get the alert message "User has been added successfully." and user gets insert in the corresponding table. moreover one strange thing is that when e get the error message "There was an error.", even then the corresponding user get inserted into the table successfully. please guide me where i am wrong and how can i get the username gets inserted with the proper successful message.
When you run the script onclick, also you make and a post back - here, try to return false to avoid the post back - write this
onclick=\"GetValue6(....); return false;\"
or this
onclick=\"return GetValue6(....);\"
because inside the GetValue6
you return false.
And when you make debug, the program waits/hold the post back because of the debug step by step - that's why its success.
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.