The formtarget attribute specifies a name or a keyword that indicates where to display the response that is received after submitting the form. The formtarget attribute overrides the target attribute of the <form> element. Note: The formtarget attribute is new for the <input> element with type="submit" in HTML5.
A response is sent back to the browser The form processor script sends a response indicating the success or failure of the form processing operations back to the server. The response could be to re-direct to another web page.
There are 2 general ways to show a message after submitting an HTML form: Use Javascript AJAX to submit the form and show a message when the processing is complete. Submit the form as usual, and have the server-side script pass back a flag to show the message.
Most HTML forms have a submit button at the bottom of the form. Once all of the fields in the form have been filled in, the user clicks on the submit button to record the form data. The standard behaviour is to gather all of the data that were entered into the form and send it to another program to be processed.
You won't be able to do this easily with plain javascript. When you post a form, the form inputs are sent to the server and your page is refreshed - the data is handled on the server side. That is, the submit()
function doesn't actually return anything, it just sends the form data to the server.
If you really wanted to get the response in Javascript (without the page refreshing), then you'll need to use AJAX, and when you start talking about using AJAX, you'll need to use a library. jQuery is by far the most popular, and my personal favourite. There's a great plugin for jQuery called Form which will do exactly what it sounds like you want.
Here's how you'd use jQuery and that plugin:
$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
})
;
An Ajax alternative is to set an invisible <iframe>
as your form's target and read the contents of that <iframe>
in its onload
handler. But why bother when there's Ajax?
Note: I just wanted to mention this alternative since some of the answers claim that it's impossible to achieve this without Ajax.
The non-jQuery vanilla Javascript way, extracted from 12me21's comment:
var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php");
xhr.onload = function(event){
alert("Success, server responded with: " + event.target.response); // raw response
};
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm"));
xhr.send(formData);
For POST
's the default content type is "application/x-www-form-urlencoded" which matches what we're sending in the above snippet. If you want to send "other stuff" or tweak it somehow see here for some nitty gritty details.
Future internet searchers:
For new browsers (as of 2018: Chrome, Firefox, Safari, Opera, Edge, and most mobile browsers, but not IE), fetch
is a standard API that simplifies asynchronous network calls (for which we used to need XMLHttpRequest
or jQuery's $.ajax
).
Here is a traditional form:
<form id="myFormId" action="/api/process/form" method="post">
<!-- form fields here -->
<button type="submit">SubmitAction</button>
</form>
If a form like the above is handed to you (or you created it because it is semantic html), then you can wrap the fetch
code in an event listener as below:
document.forms['myFormId'].addEventListener('submit', (event) => {
event.preventDefault();
// TODO do something here to show user that form is being submitted
fetch(event.target.action, {
method: 'POST',
body: new URLSearchParams(new FormData(event.target)) // event.target is the form
}).then((resp) => {
return resp.json(); // or resp.text() or whatever the server sends
}).then((body) => {
// TODO handle body
}).catch((error) => {
// TODO handle error
});
});
(Or, if like the original poster you want to call it manually without a submit event, just put the fetch
code there and pass a reference to the form
element instead of using event.target
.)
Docs:
Fetch: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
Other: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript That page in 2018 does not mention fetch (yet). But it mentions that the target="myIFrame" trick is deprecated. And it also has an example of form.addEventListener for the 'submit' event.
I am doing it this way and its working.
$('#form').submit(function(){
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data : $('#form').serialize(),
success: function(){
console.log('form submitted.');
}
});
return false;
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With