Share via

Stopping POST Behavior from INput Button

Kmcnet 1,376 Reputation points
2025-03-27T22:20:55.7933333+00:00

Hello everyone and thanks for the help in advance. I am developing an Asp.Net Core application that uses jQuery ajax to post data to a controller that returns a partial view to update the page. Since this is an ajax call, I don't want return the entire page, instead wanting only to update a small portion. I have attempted to override the button click:

$(document).ready(function () {
    $('#btnupload').off('click').on('click', function (event) {
        event.preventDefault();
        let form = $("#frmupload");
        let url = form.attr('action');
        $.ajax({
            type: "POST",
            url: url,
            data: form.serialize(), // Serialize form data
            success: function (response) {
                $("#divRESPONSE").html(response);
            },
            error: function (data) {
                alert("Error occurred while submitting the form");
            }
        });
    });
});

And the HTML

                    <form id="frmupload" name="frmupload" method="post" action="/Controller/Upload">
                        <input type="hidden" id="ID" name="ID" value="123" />
                        <input id="btnupload" name="btnupload" type="submit" value="Upload" />
                    </form>

When the button is clicked, the form posts to /Controller/Upload, but ends up displaying the returned partial view like a complete page.

The controller looks like:

        [HttpPost]
        public IActionResult Upload(int ID) 
        {


            // do some database stuff

            return PartialView("~/Views/Shared/_PartialView.cshtml");

        }

Any help would be appreciated.

Developer technologies | ASP.NET Core | Other

4 answers

Sort by: Most helpful
  1. Danny Nguyen (WICLOUD CORPORATION) 7,025 Reputation points Microsoft External Staff Moderator
    2025-08-01T05:30:13.6466667+00:00

    Hi @Kmcnet ,

    Since you have had great help here on this thread, I would like to chime in with extra information that might be of help.

    Your issue is likely caused by a race condition between the browser’s default form submission and the JavaScript event handler. Since the form uses <input type="submit">, the browser may begin submitting the form before JavaScript finishes running event.preventDefault(). On slower devices or when the page is under load, this race becomes more noticeable. The result is that the AJAX call is skipped, and the browser processes a full-page reload with the server’s partial view. Handling the form’s submit event instead of the button’s click event may avoid this timing issue.


    I suggest handling it this way:

    Instead of binding the click event on the submit button, attach the handler to the form’s **submit **event. This approach is more reliable across different devices and browsers. It ensures the default form submission is intercepted no matter how the form is submitted—by pressing Enter, clicking the button, or triggering a .submit() call in code.

    
    $(document).ready(function () {
    
        $('#frmupload').on('submit', function (event) {
    
            event.preventDefault(); // Prevent default form submission
     
            let form = $(this);
    
            let url = form.attr('action');
     
            $.ajax({
    
                type: "POST",
    
                url: url,
    
                data: form.serialize(),
    
                success: function (response) {
    
                    $("#divRESPONSE").html(response);
    
                },
    
                error: function (data) {
    
                    alert("Error occurred while submitting the form");
    
                }
    
            });
    
        });
    
    });
    
    

    While trying this, keep type="submit" to catch submission paths at the form level.


    Hope this helps resolve your issue, please let me know if it works out for you.

    Was this answer helpful?

    1 person found this answer helpful.

  2. Bruce (SqlWork.com) 84,071 Reputation points
    2025-03-30T15:08:04.2033333+00:00

    View source and check the jquery link is before the code. Also check the browsers console for errors.

    Was this answer helpful?


  3. AgaveJoe 31,361 Reputation points
    2025-03-28T10:28:07.8666667+00:00

    If you're seeing a full page refresh after submitting the form, it means the AJAX request isn't working as intended. To pinpoint the issue, use your browser's Developer Tools and strategically place console.log() statements within your JavaScript code. This will help you track the flow of data and identify where the script is failing.

    The example below demonstrates how to handle form submissions using AJAX, focusing on the form's submit event rather than a button click.

    @{
        ViewData["Title"] = "Ajax";
    }
    <form id="frmupload" name="frmupload" method="post" action="/Ajax/Upload">
        <input type="hidden" id="ID" name="ID" value="123" />
        <input id="btnupload" name="btnupload" type="submit" value="Upload" />
    </form>
    <hr />
    <div id="divRESPONSE"></div>
    
    @section scripts {
    
    <script>
            $(document).ready(function() {
              $('#frmupload').submit(function(event) {
                event.preventDefault();
    
                const form = $("#frmupload");
                const url = form.attr('action');
    
                $.ajax({
                  type: 'POST',
                  url: url,
                  data: $(this).serialize(),
                  dataType: 'html',
                  success: function(response) {
                    console.log(response);
                    $('#divRESPONSE').html(response);
                  },
                  error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                    $('#divRESPONSE').html('<p style="color: red;">An error occurred.</p>');
                  }
                });
              });
            });
    </script>
    }
    
    

    Was this answer helpful?


  4. SurferOnWww 6,016 Reputation points
    2025-03-28T00:35:50.7433333+00:00

    Stopping POST Behavior from INput Button

    Isn't event.preventDefault(); working?

    If not, please try changing

    <input id="btnupload" name="btnupload" type="submit" value="Upload" />

    to

    <input id="btnupload" name="btnupload" type="button" value="Upload" />

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.