0

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";
        }
    }
}
5
  • "$('#Button1')" - That's referencing the server-side ID. Is that client-side ID different? Commented Nov 20, 2013 at 16:09
  • The client side ID will be the same since the ClientIDMode is set to Static Commented Nov 20, 2013 at 16:11
  • Why are you returning a string with a value of "True" from the web method, just to have the jQuery success handler ignore it? ASP.NET AJAX Page Methods allow for the void return type. Commented Nov 20, 2013 at 16:11
  • 2
    Have you tried using a standard HTML button instead of the ASP:Button? I've heard of some problems when using jQuery with ASP buttons. Commented Nov 20, 2013 at 16:14
  • By the way your code is open to SQL injection. Please use SQL params in production code Commented Nov 20, 2013 at 16:19

3 Answers 3

1

Use e.preventDefault(). This will stop your button from submitting the form.

$('.demo').on('click','#Button1', function (e) {
    e.preventDefault(); //stops from refreshing.
    //Your code.
});

But again, you don't have to use .net controls for this.

Sign up to request clarification or add additional context in comments.

2 Comments

The button is not dynamic so .click() should work, but event delegation is not a bad idea. Under the covers that is what jQuery is using anyway.
@KarlAnderson - you're right. I changed my answer. OP is submitting the form & I think that's not what he wants(he needs ajax). e.preventDefault() will stop the page from refreshing.
0

Change your button to a standard HTML control:

  <asp:Button ID="Button1" runat="server" Text="Button" ClientIDMode="Static"    />

becomes

  <input type="text" ID="Button1" text="Button" />

This avoids causing an ASP.NET postback when the button is clicked.

And please note that your database code is open to SQL injection!

Furthermore the ids are wrong in the JS:

   <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':'" + $('#txtUsername').val() + "','Email':'" + $('#txtEmail').val() + "'}",
                   async: false,
                   Success: function (response) {
                   $('#txtUsername').val(''),
                   $('#txtEmail').val(''),
                       alert("User has been added successfully.");
                       window.location.reload();
                   },
                   error: function () { alert("error"); }
               });

           });
       });
</script>

3 Comments

I have added html control but the data is not saved in database i have updated my above code, Is there any issue in ajax code..
If you use a tool like fiddler, firebug, etc can you see the request being made? Are there any errors?
The ids of your textboxes are wrong. You need to update the ids of TextBox1 and TextBox2. See my update on my answer
0

Try referencing your button by a class name instead of by ID, like this:

<asp:Button ID="Button1" runat="server" Text="Button" CssClass="TheButton" />

Now in your jQuery selector do this instead:

$('.TheButton').click(function () {

This allows you to get away from having to deal with the name mangling issue with ASP.NET server controls.

4 Comments

in .NET 4+ you can also set ClientMode="Static" which is what the OP is doing
I realize that the client mode should not cause name issues, but using the class name definitely will not; thus why I suggested it.
I agree that what you suggest is better practice
I have checked by replacing id with class but the data is not saved in database, is there any problem with Ajax.. thanks for the suggestion

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.