How to submit an HTML form without redirection

Issue

If I have a form like this,

<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>

how can I submit it without redirecting to another view by JavaScript/jQuery?

I read plenty of answers from Stack Overflow, but all of them redirect me to the view returned by the POST function.

Solution

In order to achieve what you want, you need to use jQuery Ajax as below:

$('#myForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: '/Car/Edit/17/',
        type: 'post',
        data:$('#myForm').serialize(),
        success:function(){
            // Whatever you want to do after the form is successfully submitted
        }
    });
});

Also try this one:

function SubForm(e){
    e.preventDefault();
    var url = $(this).closest('form').attr('action'),
    data = $(this).closest('form').serialize();
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        success: function(){
           // Whatever you want to do after the form is successfully submitted
       }
   });
}

Final solution

This worked flawlessly. I call this function from Html.ActionLink(...)

function SubForm (){
    $.ajax({
        url: '/Person/Edit/@Model.Id/',
        type: 'post',
        data: $('#myForm').serialize(),
        success: function(){
            alert("worked");
        }
    });
}

Answered By – Amin Jafari

Answer Checked By – Marie Seifert (AngularFixing Admin)

Leave a Reply

Your email address will not be published.