Is it possible to refresh a form only? - javascript

I have a form that when is submited it posts to a div. Ok, so I found the issue that i was getting double submissions, so i tried to apply some jquery plugins i found, but they were useless because if you double clicked fast enough I still got a double submission. From those I found i saw the best way to prevent it was with
if (this.beenSubmitted) return false;
else
this.beenSubmitted = true;
but then, I noticed that if the form needed to be sent again, the user would have to refresh the page in order to send it. In my case, I want them to be able to send again after is sent, (Im not contradicting myself, because it would be diferent content). To explain it better, this form post ideas. If you want to post 2 diferent ideas you would have to refresht he page to post. Preventing double submission would help from submitting the same idea twice if you clicked fast enough. So, what I did is that I added this "5000":
if (this.beenSubmitted) return false, 5000;
else
this.beenSubmitted = true;
So, now it refreshed my page. But im a little picky, lol. So I find it annoying that the whole page has to refresh. What if your typing and then it refreshes. I can always lower the 5000 I know, but I still find it annoying in case you start to browse the website or to zoom in, you end up refreshed.
So, my question is, is there any way to just refresh the form? or a better way to prevent double submission that actually works for this case (that ur able to submit after a few secs) ?
this is script:
<script type="text/javascript">
$(document).ready(function(){
$("form#myform").submit(function() {
var addcontent = jQuery('#addcontent').attr('value');
if ( addcontent.replace(/\s/g,"") == "" ) return false;
if (this.beenSubmitted) return false,5000;
else
this.beenSubmitted = true;
$.ajax({
type: "POST",
url: "post.php",
data:"addcontent="+ addcontent,
success: function(){blah blah blah, ton sof code here including pagintion here, insert into a div here also, if u need this let me know.
});
</script>
Most of that I did it from asking questinos here. My Jquery and Ajax knowledge isnt the best one.
THanks for the help =}

Rate limiting to prevent malicious behavior in ExpressJS
The above link has something about putting a timer on the submit button so that you can't click it again within 3 seconds.
<script>
var submitTimer = new Collate(3000);
</script>
<form action="post" onsubmit="return submitTimer.idle();">

why don't u use the this.beenSubmitted = true approach and combine it with a timeout? for example after 5000ms u execute the timeout and set this.beenSubmitted to false.

The statement:
return false, 5000;
will always return 5000, the use of false is redundant and pointless.
To reset a form without reloading the page (which won't necessarily reset the form in some browsers), use a reset button or call the form's reset method. You can use an onreset listener to update the beenSubmitted property if the form is reset.
Multiple submission of a form has been an issue since forms were invented, it's usually dealt with at the server (if two identical requests are received, ignore the second).
Using script at the client is unreliable since you don't know what the server is doing and you have to guess whether or not the form needs to be resubmitted.

Related

Why does HTML change back after Javascript runs

I have this script performed on submit:
function analyze() {
var answer = document.forms["questions"]["answer1"].value;
var item = document.getElementById("content");
item.innerHTML=answer;
}
Script is performed, but div doesn't keep the value, it changes back.
When you do a submit, your page is going to re-render, causing all of your elements to get back to their initial state. So changing the your div or whatever you have in the HTML with class content is going to reset to being back to being blank.
You probably want to save the answer in Browsers LocalStorage or some sort of data structure and then request it out of there.
Save your answer value to localStorage or sessionstorage and then show the same value in your div. If you are submitting form then it will re-load the page and clear the innerHTML of div.
A submit button causes the page to rerender. You have a number of options to prevent that:
Don't use a submit button, use a normal button that happens to SAY submit. You would then run the function "onClick" for the button, not "onSubmit" for the form. (this is what I recommend)
Return false from that function and/or call PreventDefault.
Actually submit it to the server and have the server do the work and return the page (probably not a good choice for performance reasons).
EDIT: you could do something with local or session storage, but that seem a bit rube-goldburg for the problem you have.

Form submission blocking issues

I'm new here in terms of asking questions, but I have read many articles/questions/answers for quite some time now. My question is about part of a code that got me stuck for some time now.
So in my project I've got a registration form that has an JS validation and server side validation. Now what I wanted to do is disable form submitting before the JS validation is ok and I've set some conditions for it to be like that. Now the problem occured when those conditions were met. I used this line to stop form from submiting:
$('.memberReg').on('submit',function(){return false;});
In a situation like this for instance:
if(response.okText == 'SUCCESS' && response.warning == null )
{
$('label[for="email"]').addClass("success");
$('label[for="email"]').append("<span> is not yet registered!</span>");
console.log(result);
}else
{
$('label[for="email"]').addClass("error");
$('label[for="email"]').append("<span> is already taken!</span>");
$('.memberReg').on('submit',function(){return false;});
}
What happens here is that I do block the form from submiting, but it is blocked entirely, even when the other conditions are met. In this example even with correct email you cannot submit anymore.
I have tried using a variable with true-false statements that would make a validForm() function submit the form, but the function starts looping and it is still not enabling the form.
I also tried using return true for the form submit in the valid email part, still the same effect.
Anyone knows how to block it only on a certain condition without blocking it entirely so that the user has to refresh if he wants to send?
I believe I figured it out, after a few test runs it works smoothly, so I will post it in case someone else might have the same problem.
So at start I used:
$('.memberReg').on('submit',function(){return false;});
Which was overwriting the submit handler as one of the good people told me in one of his answers. So I tried changing my approach to the way I want to implement it and used:
$( ".memeberReg" ).submit(function( event ) {
if ( condition ) {
//successfulValidationCode
return;
}
//errorCode
event.preventDefault();
})
Under conditions I am checking the variables that I set in my field validations and in case of a bad input i use event.preventDefault(); to block the form again.
The problem is that you're overwriting the submit handler, and once it is overwritten, it is gone until the page is reloaded. I would question this approach entirely to be honest; you shouldn't have to overwrite the submit handler to prevent the form being submitted.
By the way, you're using JavaScript validation, not AJAX validation. AJAX is the process of sending a request to the server, and potentially receiving a result, without refreshing the page

When I disable submit button (after form submit) the page does not load

I have an HTML form which submits to another page via POST. Nothing special about it, except that after the form validates I try to hide and/or disable the submit button so that it cannot be double-submit, while also telling the user the next page might take a while to load.
The relevant code is:
jQuery(document).ready(function () {
jQuery("form#form").submit(function() {
var result = validate();
jQuery(this).find('input[type=submit]').prop('disabled', true);
jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html()+
"<br/><br/><span style='margin: 25px; padding: 5px; background: yellow; "+
"width: 100%; font-weight: bold;'>Loading... this may take a few minutes! "+
"<i class='fa fa-spinner fa-spin' style='color: blue;'></i></span>");
return result;
});
});
function validate() {
return true; // Does stuff, then returns a simple true or false
}
By request, here is the (very simple) button wrapper HTML:
<div class="col-sm-12" id="submit-button-wrapper">
<input type="submit" value="One More Step" />
</div>
When the I remove the which changes the button wrapper's HTML, the form submits just as you'd expect. When I have that line in, however, it still calls the next page and executes that code, without the displayed page ever changing.
I have tested in both Chrome and Firefox, so I know it's not a browser issue, but this is really weird behavior. What am I doing wrong?
My goal: (1) validate the user's input, (2) give the user a clue that the page is going to take a while to load and (3) display the output from the action="complete.php" page once the PHP on it has run.
Maybe you can achieve this with $ajax and show results on the same page.
Send POST data to /some.php
After sending data, give feedback to user changing button behavior
When the task is complete, receive data and verify success or error and act accordingly. If OK, change button text to "complete!" or something else, and append response data to some div. If NOT OK, give feedback as well.
In code:
$("form#form").submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "some.php",
data: $(this).serialize(),
dataType : 'json',
timeout: 2000,
cache: false,
afterSend: function() {
/*change button behavior here*/
},
success: function(result) {
if (result === "ok"){
/*maybe append data to div and update button text to complete*/
} else {
/*if result not ok, send feedback*/
}
}
});
});
BTW: ajax documentation http://api.jquery.com/jquery.ajax/
When you return true (if validated) then the form is submitted. However, you're changing the DOM / submit button wrapper and essentially removing the submit button, right? Likely that is what is causing your problem. Leave the submit button wrapper alone. If you want to display a message display it as an overlay or hide the submit button wrapper and show the message wrapper in its place, don't remove the submit button altogether.
I know that you're just showing a slight jQuery and HTML portion of the script, but that isn't quite enough to figure out your problem. Since not all of it seems to be there because you mention action="complete.php" but I don't see that within your jQuery or HTML sample of code. So I have a few questions of my own.
Is the form small or large. If it's a small form then why aren't you displaying the output on the submit page? You could do that with what you currently have but a single PHP or ASP page could save you on amount of pages to make and what not. As a side note, depending on size of the form, you can do the validation on same page or continue to use action="" for it if large.
Do you have need for a database file or are you saving to one? If you do/are, you could write to the DB file, have the submit open the next page and view what was saved in the database on that new page. Again, you can probably use a single PHP or ASP page.
This last part sounds more valid for your purpose. You could use location.href="http://www.domain.com/home.html";
or use window.location("http://www.domain.com/home.html"); to redirect to the new page.
On another matter about some of the comments others made.
You don't exactly need the + unless you're dividing each of those out into their own separate lines when you could just use one line to do that. That's probably what confused Rajesh about the '. In fact I'm not sure why you yourself mentioned the + when referring to Rajesh comment about "concat string" and "append" ,because those two have nothing to do with the +. In fact to take a guess, he might have been referring to your jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html() which kinda looks like a concat string.
Speaking about append, not really needed unless for example you're doing something like giving the user the option to add rows to a form question.

reload php page with javascript

I have drawn a chess board in a php page. Every piece is set as draggable, and every tile as droppable. Once a piece is dropped on a tile, I'd like to reload the php page so the board can be drawn anew along with new positions.
How can I do that: reloading the php page with javascript, without displaying a window asking for confirmation such as "To display this page, Firefox must send information that will repeat any action (such as a search or order confirmation) that was performed earlier. ->Cancel; Resend" ?
Or perhaps there are better solutions?
If you want to avoid having refresh reporting data (for any reason, including the user clicking the reload button) then use the POST-REDIRECT-GET pattern (http://en.wikipedia.org/wiki/Post/Redirect/Get). Read that, it will explain what to do.
Quick solution: you could try:
window.location.reload(true); //true sets request type to GET
Use GET, instead of POST and the dialog box you are getting will go away.
Good luck!
Make use of
window.location.reload();
will refresh automatically
<script>
var timer = null;
function auto_reload()
{
window.location = 'http://domain.com/page.php'; //your page location
}
</script>
<!-- Reload page every 10 seconds. -->
<body onload="timer = setTimeout('auto_reload()',10000);">
reference http://davidwalsh.name/automatically-refresh-page-javascript-meta-tags

onBeforeUnload and multiple forms

I want to have a feature to submit several forms on a page when the user leaves the page. There is this "do you wanna save?" question and my code so far is like this:
function checkForChanges( ) {
if (window.formform1Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form1.submit();
}
}
if (window.formform2Changed == true) {
if (window.asked == false) {
window.asked=true;
doSave = confirm("Wanna save? Click OK.")
}
if (window.doSaveForms || doSave) {
window.doSaveForms = true;
document.forms.form2.submit();
}
}
}
It may seem a little bit of overkill but it is generated automatically by our template engine and may be extended to more forms.
The body tag:
<body
onLoad="init();
window.formform1Changed=false;
window.asked=false;
window.doSaveForms=false;
window.formform2Changed=false;"
onbeforeunload="checkForChanges();">
And interesting part of one of the forms (the other one looks identically:
<input value="xyz" id="la" onchange="window.formform1Changed=true;" />
<input name="save" onclick="window.formform2Changed=false; window.formform1Changed=false;" type="submit" value="save" />
Now to the problem:
If I change values in both forms and navigate away from the page, the question from the first form pops up. I click OK, the form is saved but the form1.submit() triggers a new onBeforeUnload event which breaks the whole logic of my idea.
The question now would be if there is a way to submit all forms on a page when only asking one time when the user navigates away?
Any help is highly appreciated!
Thanks.
Form submissions requires post-back, once you submit the first form, your page is redirected to the "action" of that form and you will lose the information in the rest of the forms you have.
Having multiple forms on the page is not the best idea, however, if you absolutely have to have them, the way to save all of them would be to replace full post-back with an AJAX call to a web-service (or a stand-alone page, that accepts query string parameters, though it's not as secure or flexible way). That way you can submit each form over the AJAX call without page redirecting.
As SLaks said, you will not be able to submit multiple forms in the way you are trying. You do have some other options though. Instead of traditional form submits you could make some kind of ajax calls to save the form data you care about. Here is an example using jquery and php (link)

Categories

Resources