Infinite form submit with $(document).ready - javascript

i want to create a post form it'll get data from my url and post it to my database.
When i clicked the "Add" buton its working fine but when i try to add with $(document).ready function, I'm getting infinite loop. (My goal is submitting form every time i execute the file)
I've no knowlage about jquery and Im using this code:
<script type="text/javascript">
$(document).ready(function () {
document.forms["form1"].submit();
});
</script>
How can I get rid off infinite loop?

I'm guessing your form does not have action-attribute, hence it posts to itself. Add action attribute to the page you want to post to:
<form action="mypage.html"....

You will have to use cookie to store first load information and check it before submitting form. Set the expire time as per your project requirement. Before using jQuery cookie, you have add cookie plugin after jQuery library.
jQuery Cookie: jQuery Cookie plugin.
<script type="text/javascript">
$(document).ready(function () {
if (! $.cookie("cookieName")){
document.forms["form1"].submit(); // do your stuff
$.cookie("cookieName", "firstSet", {"expires" : 7}); // set cookie now
}
});
</script>
Hope will help!

Can you try?
$(document).one("ready",function(){
// submit form here
});

Use below code.
<form action="yourformname.html" method="post" enctype="multipart/form-data">
</form>
<input type="submit" value="Submit">
If there is any file upload control, then use enctype in form tag.

Maybe a flag can do the job.
var flag = true;
$(document).ready(function(){
if(flag){
// submit code here
flag = false;
}
});

Inside your form paste this line,
<input type="hidden" name="ispost" value="0" id="ispost">
And in jQuery add this, your issue will be resolved
<script type="text/javascript">
$(document).ready(function() {
if($('#ispost').val() != 'submit')
{
$('#ispost').val('submit');
$('#form1').submit();
}
});
</script>

Related

Submit form with data on load

This data on console $(this).serialize() gives me the result below, I wanted to submit it on load not on click and pass a select default value programatically(currency_code) -- the form is a built in library
_method=PUT&source=geolocation_recommendation&return_to=%2F&currency_code=PHP
This is my code on click
$(document).ready(function () {
$(document).on("submit", "form.locale-bar__form", function (e) {
e.preventDefault();
let data = $(this).serialize()
console.log('>>>>', data)
});
});
Form looks like this
Am I missing the point or is this not doing its job? :
$(document).ready(function(){
$(".locale-bar__form").submit();
});
edit:
might find your solution here
Another HTML solution:
<html>
<body onload="document.locale-bar__form.submit()">
<form action="#" name=".locale-bar__form">
<!-- Your form here -->
</form>
</body>
</html>
edit:
You can add selected attribute to an option with jquery like this. So that it will make that option default.
$("select option[value='blabla']").attr("selected","selected");

Javascript automatically trigger button to submit php form with dynamic action link

I'm having a form with its action link created dynamically.
Basically the page is populated with pagination and the form action link is different for 1st page and last page. I have a timer running and when timeout I want the form to be submitted.
Now here is the problem. During timeout if the user is on 1st page, the javascript submit function submit with the dynamic action link created for 1st. My original purpose is to submit the form for the last page action link.
<form method="post" id="submitmyform" <?php if($page==$firstpage){?> action="1st/page/action/link"<?php }elseif($page==$lastpage){?>action="last/page/action/link"<?php } ?> >
<?php if($page==$firstpage){?>
<input type="hidden" name="firstpagecontent1" value="somthing" >
<input type="hidden" name="firstpagecontent2" value="somthingelse" >
<button type="submit" id="firstpagebutton" name="firstpagebtn" value="1">
<?php }elseif($page==$lastpage){?>
<input type="hidden" name="lastpagecontent1" value="somthing" >
<input type="hidden" name="lastpagecontent2" value="somthingelse" >
<button type="submit" id="lastpagebutton" name="lastpagebtn" value="2">
<?php } ?>
</form>
<script>
function ontimeout{
var button = document.getElementById('lastpagebutton'),
form = button.form;
form.addEventListener('submit', function(){
return true;
})
}
</script>
I have no problem with the PHP part. I'm only trying to figure out how JS can work for me. The above JS is not working. It frequently submit but not with the last page values. Could anyone please guide me to find out where I'm stuck and possibly show a way.
Note: Above code is only illustration to give the concept. I have not included the pagination here as its long piece of code as a whole and I'm only having problem with JS.
Many Thanks in advance.
setTimeout(function(){
// Invoke function every 10 minutes
$('#lastpagebutton').trigger('click');
}, 600000);
Using jquery
Since you're using PHP to change the form action, until you got to the last page there is not access to the action value, meaning it won't take place in the form submit action while it is a different page than the last one.
I would suggest having that last page url/action in a different php variable, so it can be used as for JS expiration/redirection anytime. Something like:
1: Timeout - Redirection last page
<?php
$lastPageUrl = 'https://example.com';
?>
<script type="application/javascript">
setTimeout(function() { timeOut() }, 3000);
function timeOut() {
var lastPage = "<?= $lastPageUrl ?>";
location.replace(lastPage);
}
</script>
2: Timeout - Update form action last page
<script type="application/javascript">
function timeOut() {
var form = document.getElementById('submitmyform');
form.action = '<?= $lastPageUrl ?>';
}
</script>

How to call function after submit form aspx

I want callback alert after submit form, but doesn't worked. Submit not execute.
Only $("#formImpressao").submit(); worked fine.
I try too use $(document).ready(function () { ... :( No Success
Whats wrong?
Sorry for my bad english
<div id="HiddenFormTarget" style="display:none;">
<form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>
<iframe id="frmPrint" name="frmPrint" width="0" height="0" runat="server">
</iframe>
<script language="javascript" type="text/javascript">
$("#formImpressao").submit(function () {
alert('Test');
});
$("#formImpressao").submit();
</script>
$("#formImpressao").submit(function (e) {
e.preventDefault();
alert('Test');
//Insert AJAX to submit form data
});
e.preventDefault() will prevent the default action of the submit event, and then run your alert, but it will NOT submit the form. For that, you will need to use AJAX. It's simple enough to understand, and there are plenty of SO topics on the use of it, so I won't reiterate. But preventDefault() will get you started.
<form id="formImpressao" method="post" target="frmPrint" action="/VisualizarRelatorios/ImprimirRelatorio.aspx""></form>
</div>
Now you can use two ways to submit the form using only jQuery,Recommended method
<script>
$(document).ready(function(){
//instead of id selector use tag selector
$("form").submit(function () {
alert('Test');
});
});
</script>
Another using id selector which is already posted
I reproduce this situation and all right:
[https://codepen.io/piotrazsko/pen/mqMrgo][1]
(1) There appears to be an extra quote in your form tag.
(2) Have you tried your approach without the target attribute in the form tag?
e.g. -
<form id="formImpressao" method="post" action="/VisualizarRelatorios/ImprimirRelatorio.aspx"></form>

Post a form and put results in a div

I can't get my form to submit correctly using jquery. I have tried using the tips here: https://api.jquery.com/jQuery.post/ and http://api.jquery.com/submit/ but can't figure out what I am missing to have the form submit and return the results to the div instead of reloading the page. It is supposed to call an external php page to get processed and return the results.
<script>
// On click "button.submit"
$("input[id^=formsubmit]").submit(function( event ) {
// Stop form from submitting normally
event.preventDefault();
$.get( "functions.php?do=adminmenu", function( data ) {
$( \".contentarea\" ).html( data );
});
return false;
});
</script>
<form action="#" name="submitForm">
<input type="textbox" name="test">
<input type="submit" value="Save Settings" id="formsubmit">
</form>
<div class="contentarea"></div>
Try to wrap your code inside DOM ready handler $(function() {...}); to make sure your DOM elements have been properly loaded.
Also, you can remove return false here as well as there's no need to escape the $(".contentarea" ) using \. So try this code:
$(function () {
$("input[id^=formsubmit]").submit(function (event) {
// Stop form from submitting normally
event.preventDefault();
$.get("functions.php?do=adminmenu", function (data) {
$(".contentarea").html(data);
});
});
});
The problem is that you're not passing the data to the php file. Furthermore you have not specified the type of data handled. And if you want to use POST you should use $.post(); and not $.get();
Try it like this: I've changed the function from .get to .post, added the data you want to send to the php file and specified a data type.
<script>
$(document).ready(function () {
$('#formsubmit').click(function () {
$.post("functions.php?do=adminmenu",{test_val:$('#test_input').value},function (data) {
$('.contentarea').html(data);
},"json");
});
});
</script>
<input id="test_input" type="text" value="">
<input id="formsubmit" type="submit" value="Save Settings">
<div class="contentarea"></div>
Last point: What is the php file returning? Is it only a string or what? Depending on this you need to modify the function writing the returned content in the '.contentarea'.
And by the way: When submitting the information via AJAX you don't need a form around it, as it just creates the need to escape the default behaviour when submitting a form.
If it still doesn't work let me know, I'll help you.

How to prevent form from submitting multiple times from client side?

Sometimes when the response is slow, one might click the submit button multiple times.
How to prevent this from happening?
Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.
EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.
$("body").on("submit", "form", function() {
$(this).submit(function() {
return false;
});
return true;
});
I tried vanstee's solution along with asp mvc 3 unobtrusive validation, and if client validation fails, code is still run, and form submit is disabled for good. I'm not able to resubmit after correcting fields. (see bjan's comment)
So I modified vanstee's script like this:
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
Client side form submission control can be achieved quite elegantly by having the onsubmit handler hide the submit button and replace it with a loading animation. That way the user gets immediate visual feedback in the same spot where his action (the click) happened. At the same time you prevent the form from being submitted another time.
If you submit the form via XHR keep in mind that you also have to handle submission errors, for example a timeout. You would have to display the submit button again because the user needs to resubmit the form.
On another note, llimllib brings up a very valid point. All form validation must happen server side. This includes multiple submission checks. Never trust the client! This is not only a case if javascript is disabled. You must keep in mind that all client side code can be modified. It is somewhat difficult to imagine but the html/javascript talking to your server is not necessarily the html/javascript you have written.
As llimllib suggests, generate the form with an identifier that is unique for that form and put it in a hidden input field. Store that identifier. When receiving form data only process it when the identifier matches. (Also linking the identifier to the users session and match that, as well, for extra security.) After the data processing delete the identifier.
Of course, once in a while, you'd need to clean up the identifiers for which never any form data was submitted. But most probably your website already employs some sort of "garbage collection" mechanism.
Here's simple way to do that:
<form onsubmit="return checkBeforeSubmit()">
some input:<input type="text">
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var wasSubmitted = false;
function checkBeforeSubmit(){
if(!wasSubmitted) {
wasSubmitted = true;
return wasSubmitted;
}
return false;
}
</script>
<form onsubmit="if(submitted) return false; submitted = true; return true">
The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"
Just Disable the form submit button, like below code.
<form ... onsubmit="buttonName.disabled=true; return true;">
<input type="submit" name="buttonName" value="Submit">
</form>
It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.
Create a unique identifier (for example, you can hash the current time), and make it a hidden input on the form. On the server side, check the unique identifier of each form submission; if you've already received that hash then you've got a repeat submission. The only way for the user to re-submit is to reload the form page.
edit: relying on javascript is not a good idea, so you all can keep upvoting those ideas but some users won't have it enabled. The correct answer is to not trust user input on the server side.
Disable the submit button soon after a click. Make sure you handle validations properly. Also keep an intermediate page for all processing or DB operations and then redirect to next page. THis makes sure that Refreshing the second page does not do another processing.
You could also display a progress bar or a spinner to indicate that the form is processing.
Using JQuery you can do:
$('input:submit').click( function() { this.disabled = true } );
&
$('input:submit').keypress( function(e) {
if (e.which == 13) {
this.disabled = true
}
}
);
I know you tagged your question with 'javascript' but here's a solution that do not depends on javascript at all:
It's a webapp pattern named PRG, and here's a good article that describes it
You can prevent multiple submit simply with :
var Workin = false;
$('form').submit(function()
{
if(Workin) return false;
Workin =true;
// codes here.
// Once you finish turn the Workin variable into false
// to enable the submit event again
Workin = false;
});
On the client side, you should disable the submit button once the form is submitted with javascript code like as the method provided by #vanstee and #chaos.
But there is a problem for network lag or javascript-disabled situation where you shouldn't rely on the JS to prevent this from happening.
So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.
You can try safeform jquery plugin.
$('#example').safeform({
timeout: 5000, // disable form on 5 sec. after submit
submit: function(event) {
// put here validation and ajax stuff...
// no need to wait for timeout, re-enable the form ASAP
$(this).safeform('complete');
return false;
}
})
The simpliest and elegant solution for me:
function checkForm(form) // Submit button clicked
{
form.myButton.disabled = true;
form.myButton.value = "Please wait...";
return true;
}
<form method="POST" action="..." onsubmit="return checkForm(this);">
...
<input type="submit" name="myButton" value="Submit">
</form>
Link for more...
Use this code in your form.it will handle multiple clicks.
<script type="text/javascript">
$(document).ready(function() {
$("form").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script>
it will work for sure.
This allow submit every 2 seconds. In case of front validation.
$(document).ready(function() {
$('form[debounce]').submit(function(e) {
const submiting = !!$(this).data('submiting');
if(!submiting) {
$(this).data('submiting', true);
setTimeout(() => {
$(this).data('submiting', false);
}, 2000);
return true;
}
e.preventDefault();
return false;
});
})
the best way to prevent multiple from submission is this
just pass the button id in the method.
function DisableButton() {
document.getElementById("btnPostJob").disabled = true;
}
window.onbeforeunload = DisableButton;
To do this using javascript is bit easy. Following is the code which will give desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
Most simple solutions is that disable the button on click, enable it after the operation completes. To check similar solution on jsfiddle :
[click here][1]
And you can find some other solution on this answer.
This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.
<button id="submit" type="submit" onclick="submitLimit()">Yes</button>
function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
btn.setAttribute('disabled', 'disabled');
}, 1);
setTimeout(function() {
btn.removeAttribute('disabled');
}, 2000);}
In ECMA6 Syntex
function submitLimit() {
submitBtn = document.getElementById('submit');
setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);
setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}
Just to add to the possible answers without bypassing browser input validation
$( document ).ready(function() {
$('.btn-submit').on('click', function() {
if(this.form.checkValidity()) {
$(this).attr("disabled", "disabled");
$(this).val("Submitting...");
this.form.submit();
}
});
});
An alternative to what was proposed before is:
jQuery('form').submit(function(){
$(this).find(':submit').attr( 'disabled','disabled' );
//the rest of your code
});
<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type='text' name='name' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />
</div>
</div>
</form>
<script>
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});
</script>
This is a clean Javascript code that prevents multiple valid submissions:
<script>
var form = document.querySelector('form');
form.onsubmit = function(e){
if(form.reportValidity())
// if form is valid, prevent future submissions by returning false.
form.onsubmit = (e)=> false;
return true;
}
</script>

Categories