How to submit an HTML form without redirection

JavascriptJqueryHtmlForms

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

You can achieve that by redirecting the form's action to an invisible <iframe>. It doesn't require any JavaScript or any other type of scripts.

<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>

<form action="submitscript.php" target="dummyframe">
    <!-- Form body here -->
</form>

Solution 2 - Javascript

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");
        }
    });
}

Solution 3 - Javascript

Since all current answers use jQuery or tricks with iframe, figured there is no harm to add method with just plain JavaScript:

function formSubmit(event) {
  var url = "/post/url/here";
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.onload = function() { // request successful
  // we can use server response to our request now
    console.log(request.responseText);
  };

  request.onerror = function() {
    // request failed
  };

  request.send(new FormData(event.target)); // create FormData from form that triggered event
  event.preventDefault();
}

// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
  document.getElementById(formId).addEventListener("submit", formSubmit);
}

Solution 4 - Javascript

Place a hidden iFrame at the bottom of your page and target it in your form:

<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>

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

Quick and easy. Keep in mind that while the target attribute is still widely supported (and supported in HTML5), it was deprecated in HTML 4.01.

So you really should be using Ajax to future-proof.

Solution 5 - Javascript

Okay, I'm not going to tell you a magical way of doing it because there isn't. If you have an action attribute set for a form element, it will redirect.

If you don't want it to redirect simply don't set any action and set onsubmit="someFunction();"

In your someFunction() you do whatever you want, (with AJAX or not) and in the ending, you add return false; to tell the browser not to submit the form...

Solution 6 - Javascript

You need Ajax to make it happen. Something like this:

$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
        if(name=='' || email=='' || password=='' || contact=='')
        {
            alert("Please fill in all fields");
        }
        else
        {
            // Ajax code to submit form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

Solution 7 - Javascript

One-liner solution as of 2020, if your data is not meant to be sent as multipart/form-data or application/x-www-form-urlencoded:

<form onsubmit='return false'>
    <!-- ... -->           
</form>

Solution 8 - Javascript

See jQuery's post function.

I would create a button, and set an onClickListener ($('#button').on('click', function(){});), and send the data in the function.

Also, see the preventDefault function, of jQuery!

Solution 9 - Javascript

The desired effect can also be achieved by moving the submit button outside of the form as described here:

https://stackoverflow.com/questions/26567486/prevent-page-reload-and-redirect-on-form-submit-ajax-jquery/43374240#43374240

Like this:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>

<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

Solution 10 - Javascript

Using this snippet, you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.

function submitForm(form, successFn){
    if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
        var id = form.getAttribute("id");
    } else {
        console.log("Form id attribute was not set; the form cannot be serialized");
    }

    $.ajax({
        type: form.method,
        url: form.action,
        data: $(id).serializeArray(),
        dataType: "json",
        success: successFn,
        //error: errorFn(data)
    });
}

And then just do:

var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
    console.log("Form submitted");
});

Solution 11 - Javascript

If you control the back end, then use something like response.redirect instead of response.send.

You can create custom HTML pages for this or just redirect to something you already have.

In Express.js:

const handler = (req, res) => {
  const { body } = req
  handleResponse(body)
  .then(data => {
    console.log(data)
    res.redirect('https://yoursite.com/ok.html')
  })
  .catch(err => {
    console.log(err)
    res.redirect('https://yoursite.com/err.html')
  })
}
...
app.post('/endpoint', handler)

Solution 12 - Javascript

Fire and forget vanilla js + svelte

function handleSubmit(e) {
    const request = new Request(`/products/${item.ItemCode}?_method=PUT`, { 
        method: 'POST', 
        body: new FormData(e.target),
    });
    fetch(request)
}

Used in Svelte:

<form method="post" on:submit|preventDefault={handleSubmit}>

Solution 13 - Javascript

To disable form submit. And user ajax custom for you!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDuke NukeView Question on Stackoverflow
Solution 1 - JavascriptIssa ChanziView Answer on Stackoverflow
Solution 2 - JavascriptAmin JafariView Answer on Stackoverflow
Solution 3 - JavascriptEthuil UIView Answer on Stackoverflow
Solution 4 - JavascriptSteven BlackView Answer on Stackoverflow
Solution 5 - JavascriptAnshu DwibhashiView Answer on Stackoverflow
Solution 6 - JavascriptBojan PetkovskiView Answer on Stackoverflow
Solution 7 - JavascriptAlexandre DaubricourtView Answer on Stackoverflow
Solution 8 - JavascriptNagy VilmosView Answer on Stackoverflow
Solution 9 - JavascriptJohnView Answer on Stackoverflow
Solution 10 - JavascriptjulianmView Answer on Stackoverflow
Solution 11 - JavascriptsucasaView Answer on Stackoverflow
Solution 12 - JavascriptmyleftshoeView Answer on Stackoverflow
Solution 13 - JavascriptsoliceView Answer on Stackoverflow