I had this JavaScript running on a testing host page(http://www.000webhost.com/), then I moved the form/site to another hosting page(https://www.one.com/). Suddenly the form is posted twice! I have been trying to add the following line e.stopPropagation(); to the code, right after e.preventDefault();, then noting is posted. If I only use e.stopPropagation(); - nothing is posted either.
$(document).ready(function() {
$('form').on('success.form.bv', function(e) {
var thisForm = $(this);
//Prevent the default form action
e.preventDefault();
//Hide the form
$(this).fadeOut(function() {
//Display the "loading" message
$(".loading").fadeIn(function() {
//Post the form to the send script
$.ajax({
type: 'POST',
url: thisForm.attr("action"),
data: thisForm.serialize(),
//Wait for a successful response
success: function(data) {
//Hide the "loading" message
$(".loading").fadeOut(function() {
//Display the "success" message
$(".success").text(data).fadeIn();
});
}
});
});
});
});
});
I am using 'success.form.bv', because I am using bootstrapvalidator in order to validate the form. I have not been able to combine the "Form is submitted twice" example code on the bootstrapvalidator with my code in order to only submit the form once.
What should I do in order to submit the form only once?
Related
I am building a web app, I am submitting a form with jquery, if I should click on the submit button the first time, it will sub!it once, if I should click it the second time after the first form is submitted, it will submit twice, if I could click it the third time, it will submit 3 times and so on, pls how will I prevent it. Am not talking of disabling the submit button, and I also if I should reload the page if it reset the submission
$.ajax({ type: "POST", url: url, data: data, success: success, dataType: dataType });
This is a classic example. Basically, what you want to do, in your submit method, you want to disable the submit button before you call your ajax. Once the ajax is completed, you will have 2 outcomes, success, or error. In both cases, you want to enable your submit button.
function buttonSubmit() {
let buttonSelector = event.srcElement;
buttonSelector.disabled = true;
$.post({
url: "your-api",
data: {
someData: "kjfgkdjfglkdf"
},
success: function (result) {
// handle your success, do stuff
buttonSelector.disabled = false;
},
error: function (response) {
// handle your error, do stuff
buttonSelector.disabled = false;
}
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" onclick="buttonSubmit()">Click Me!</button>
I am working on a dynamic online form website. In the main form, I have multiple sub-forms which can be added and deleted dynamically.
<div class='subform'>
//form fields
<input ...>
...
<button class='subform_submit'>
</div>
For each subform, I bind an AJAX call on the subform's submit button like this:
$('#main').on('click', '.subform_submit', function(){
// Get this subform's user input
...
$.ajax({
url: ..,
type: ..,
data: /* this subform's data */
});
});
So in that page, I may have 0 to 10 subforms depending on the user's selection.
I also have a main submit button on the bottom of the page, which can submit those subforms and the main form's data together.
$('#main').on('click', '#submit', function(e){
$('.subform_submit').click(); // Submit each subform
bootbox.confirm({ });
})
Once main submit button is clicked, I want to show a loading picture and then show a dialog box (I use bootbox.confirm() here) until all AJAX calls have completed.
This dialog box is telling user that whole form including sub-forms has been submitted.
But the problem is that each AJAX call may take 2 seconds to complete and I don't know how may calls may be pending completion. How can I write this main submit button so that it will:
Show the loading image immediately, and
Hide the loading image and show the dialog box after all AJAX calls have completed?
Keep track of how many sub-forms there are;
$subFormsCount = $('.subform').length;
Keep track of how many forms have been submitted;
$submittedForms = 0;
Each time a form finishes submitting, add to the $submittedForms;
$.ajax({
..
..
done: function(){
$submittedForms++;
}
})
Create a global timer to see if the number of submitted forms matches the total number of subforms. If true, hide the dialog box;
setInterval(function(){
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}, 50ms)
Edit
You could skip the global timer (as this will probably be a few milliseconds out) - include the check in your ajax.done instead;
$.ajax({
..
..
done: function(){
$submittedForms++;
if($submittedForms == $subFormsCount){
$('.dialog').show();
}
}
})
You want to use .done() in order to specify code that should wait until the AJAX asynchronous function completes.
$.ajax({
url:..,
type: ..,
data: /* this subform's data*/ })
.done(function() {
//Put code here
});
Have you tried .ajaxStop() event handler ?
$(document).ajaxStop(function() {
// place code to be executed on completion of last outstanding ajax call here
});
also, check this answer
I assume you have 9 subform and 1 main form.
Code for 8 subform will be same.
I use here async:false : Means next ajax will not be call until 1st one is not completed.
Sample Code Format :
var id = 5;
$.ajax({
url: ,
type: 'POST',
data: {'id':id},
dataType: 'JSON',
async: false,
error : function(xhr, textStatus, errorThrown) {
alert('An error occurred!');
},
success : function(response){
}
});
Just set variable in your last sub form that is 9th subform.
success : function(response){
var counter = true;
}
if(counter){
/* Code to show dialog.*/
}
You can use $.when to wait for each request to complete. Something like this should get you close. You'd basically want to store all the ajax requests in an array and pass that to when as the arguments.
$('#main').on('click', '.subform_submit', function () {
var formRequests = $('.subform').map(function () {
var $form = $(this);
return $.ajax({
url: '',
data: $form.serialzeArray()
});
}).get();
$.when.apply(undefined, formRequests).done(function () {
console.log('All done!');
});
});
Here goes a very similar little demo I just made up: https://jsfiddle.net/g9a06y4t/
Background:
I want to submit my HTML form asynchronously using jQuery, except if the ajax call fails. If the ajax call fails, I want to re-submit my HTML form normally.
I cannot get the "submit normally on fail" to work. What happens is if the submit button is pressed again after a fail, it submits normally, but I want the form to be resubmitted automatically on fail.
I am using namespaces because I need the generic .on('submit', ...) to always populate the hidden field.
Question:
How do I need to redesign my code so that I can achieve the functionality I desire?
Code:
$('#form).on('submit', function(event){
$(this).find('#hidden_field').val('value');
});
$('#form').on('submit.as_ajax', function(event){
event.preventDefault();
var $this = $(this);
var post = $.post({
data: $this.serialize(),
url: $this.attr('action')
});
post.done(function(response, status, xhr){
$('#container').html(response);
});
post.fail(function(xhr, status, error){
$this.off('submit.as_ajax').submit();
});
});
I think this will work for you
function submitFormNormally($this) {
$this.submit();
}
function submitFormAsAjax($this) {
var post = $.post({
data: $this.serialize(),
url: $this.attr('action')
});
post.done(function(response, status, xhr){
$('#container').html(response);
});
post.fail(function(xhr, status, error){
submitFormNormally($this);
});
}
$('#submit-button').on('click', function(event){
event.preventDefault();
var $this = $('#form');
submitFormAsAjax($this);
});
Now, what you have to do is bind the submit button like this.
I have this function. I don't understand why the form is submitted twice. Infact the request I see at the server hapijs is double.
$(function(){
$('form').on('submit', function(event){
event.preventDefault();
var $form = $(this);
$.post('/send-message', {
data: $form.serialize()
}, function(data) {
})
.fail(function(data){
});
});
});
EDIT:
I have realized that placing the script at the top is executed just once. Why?
So I have this chat,
http://codepen.io/anon/pen/Frmez
$(function() {
$('.textarea-chat').on('keyup', function(e) {
if (e.which == 13 && ! e.shiftKey) {
$(this.form).submit()
return false;
}
});
});
Updated code ^
But one problem with it is that if you input a text to send away to the chat and press enter, the chat window closes, it should stay open but I can't figure out how
$(this.form).submit()
This actually submits the <form>. You're probably getting the error "Please use POST request" because by default it uses GET. It doesn't like being sent a query string, so it gives that error. You can POST stuff to it, but nothing will happen.
In order to POST stuff to it, you need to use Ajax. See docs.
For example:
$("#myForm").submit(function () {
var url = "path/to/your/script.php"; //handle form input by your script
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), //serializes the forms elements
success: function (data) {
alert(data); //show response
}
});
return false; //avoid executing actual submit of the form
});