I am working with Ajax jquery in C#, but the click event is not called when i click on the button to save the data in a database using Ajax Jquery, the page refreshes and none of the script code executes. Please help to solve this issue. Thanks...
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css"
rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#Button1').click(function () {
alert("button clicked");
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: 'InsertDB.aspx/InsertMethod',
data: "{'Name':'" + document.getElementById('txtUsername').value + "','Email':'" + document.getElementById('txtEmail').value + "'}",
async: false,
Success: function (response) {
$('#txtUsername').val(''),
$('#txtEmail').val(''),
alert("User has been added successfully.");
window.location.reload();
},
error: function () { alert("error"); }
});
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div class="demo">
<div class="ui-widget">
<label for="tbAuto">
Enter UserName:
</label>
<asp:TextBox ID="TextBox1" runat="server" ClientIDMode="Static" Width="202px"></asp:TextBox>
<br />
<br />
Email: <asp:TextBox ID="TextBox2" runat="server" ClientIDMode="Static" Width="210px"></asp:TextBox>
<br />
<br />
<input type="submit" id="Button1" text="Button" />
</div>
</div>
</form>
</body>
</html>
InsertDB.aspx.cs
public partial class InsertDB : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public static string InsertMethod(string Name,string Email)
{
string constr = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
SqlCommand cmd = new SqlCommand("Insert into TestTable values('" + Name + "','" + Email + "')", con);
con.Open();
cmd.ExecuteNonQuery();
return "True";
}
}
}
"$('#Button1')"- That's referencing the server-side ID. Is that client-side ID different?stringwith a value of"True"from the web method, just to have the jQuery success handler ignore it? ASP.NET AJAX Page Methods allow for thevoidreturn type.