Using with AJAX
AJAX is a good option if you don't want to redirect your users after submission or if you want to add custom validation logic, that can't be performed by HTML Validations.
Basic example with vanilla JS
Let's suppose there is a following form:
<form action="https://app.form2chat.io/f/q1w2e3r4" id="contact-form" method="POST" accept-charset="UTF-8">
<input type="text" name="name">
<input type="email" name="email">
<button type="submit">Send</button>
<div id="submit-result"></div>
</form>
In this case it is only needed to paste this example code below anywhere before the </body> tag:
<script type="text/javascript">
var form = document.getElementById("contact-form");
var submitResult = document.getElementById("submit-result");
form.onsubmit = function(e) {
e.preventDefault();
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
xhr.open("POST", form.action, true);
xhr.onload = function(e) {
var response = JSON.parse(xhr.response);
if (xhr.status === 200) {
submitResult.innerHTML = "Success";
} else {
submitResult.innerHTML = "Error: " + response.error;
}
};
xhr.send(formData);
};
</script>
File uploads with AJAX
The above code will still work if your form performs file uploads.
<form action="https://app.form2chat.io/f/q1w2e3r4" id="contact-form" method="POST" accept-charset="UTF-8">
...
<input type="file" name="attachment" placeholder="Your Attachment">
...
</form>
Using jQuery
For the same form from the previous example the following code is needed to be placed before the </body> tag:
<script type="text/javascript">
$("#new_demo_form").on("submit", function(e) {
e.preventDefault();
var $form = $(this);
var $submitResult = $("#submit-result");
var payload = {};
$form.serializeArray().map((field) => { payload[field.name] = field.value});
$.ajax({
type: "POST",
url: $form.attr("action"),
data: payload,
dataType: "json",
success: function() { $submitResult.text("Success"); },
error: function(response) { $submitResult.text("Error: " + response.error); }
});
});
</script>