Question

I have this .aspx website with jQuery AJAX.

When I don't have a button, it works fine.

When I wrap AJAX call with a button, it doesn't work. There is no error, no success alert, no AJAX request, nothing in the console. It just stops. I don't know why :(

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    <script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>

    <script>
        $(document).ready(function () {
            $("#button1").click(function () {
                $.ajax({
                    url: 'WebForm1.aspx',
                    success: function (data) {
                        $('#comments').html(data);
                        console.log("success");
                    }
                });
            });
        });
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>

        <button id="button1">get recent comments</button>

        <div id="comments" runat="server">

        </div>

    </div>
    </form>
</body>
</html>
Was it helpful?

Solution

By default, the button is going to submit the form and post it. You'll want to prevent this behavior in jQuery with preventDefault():

$("#button1").click(function (event) {
    event.preventDefault();

    ... etc ...
});

Preventing the default behavior of the click event passed by jQuery into your function should make it behave as expected.


http://api.jquery.com/event.preventDefault/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top