How to submit an html form without redirecting?
If I have a form like this:
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form> how to send it without redirecting to another JavaScript / jQuery view? I read a lot of answers from StackOverflow, but they all redirect me to the view returned by the POST function.
to achieve what you want, you need to use jquery ajax as shown below:
$('#myForm').submit(function(e){ e.preventDefault(); $.ajax({ url:'/Car/Edit/17/', type:'post', data:$('#myForm').serialize(), success:function(){ //whatever you wanna do after the form is successfully submitted } }); }); UPDATED: (based on the comments below)
try it:
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 wanna do after the form is successfully submitted } }); } UPDATE 2 (OP added this part, as this was his final decision)
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"); } }); } You can achieve this by redirecting the action form to an <iframe> . It does not require JavaScript scripts or any other type.
<iframe width="0" height="0" border="0" name="dummyframe" id="dummyframe"></iframe> <form action="submitscript.php" target="dummyframe"> <!-- form body here --> </form> if you're really tricky, you can tinker with position=absolute and z-index in CSS to make sure the frame is not displayed. If that matters a lot, though maybe you might be better off using AJAX.
Put a hidden iFrame at the bottom of the page and target in the 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 although the target attribute is still widely supported (supported in HTML5), it is deprecated in HTML 4.01. So you really should use ajax for future evidence.
Well, I'm not going to tell you the magic way to do this, because no. If you have an action attribute for a form element, it will be redirected.
If you do not want it to redirect, just do not set any actions and do not set onsubmit="someFunction();"
In your someFunction() you do whatever you want (with AJAX or not), and at the end add return false; to tell the browser not to submit the form ...
Since all current answers use jQuery or iframe tricks, I suppose there is nothing wrong with adding a method with simple 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); } You need ajax for this to happen. Something like that
$(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 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; }); }); See the jQuery post function.
I would create a button and set onClickListener ( $('#button').on('click', function(){}); ) and send the data to this function.
Also see the preventDefault function, jQuery!
The desired effect can also be achieved by moving the submit button outside the form, as described here:
Prevent page reload and redirection in submit ajax / jquery form
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> Using this snippet, you can submit the form and avoid redirecting. Instead, you can pass the success function as an 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"); }); If you are managing the server side then use something like response.redirect instead of response.send
You can create your own HTML pages for this or simply redirect to what 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)