location.reload(true) starts an infinite loop [duplicate] - javascript

I have a page, to which I POST information via form method="post". I would like to relaod it with JavaScript, but location.reload(true) and location.reload() makes browsers ask if I want to send the POST data again.
I would like to make JavaScript reload the page with GET instead of POST to skip the POST data.
How can I achieve that?

window.location.href = window.location.href
try

To reload a page without post data using javascript the easiest way I've found is to use an extra form to submit - this works regardless of whether the url is # or anything.
<form name="reloadForm">
<button type="submit">
Continue
</button>
</form>
<script>
document.reloadForm.submit() ;
</script>
That will show a button briefly on screen that the user can click continue on but the script will automatically submit it - this method sorts out a number of problems - the form is empty so it will not submit any post data (the button isn't named so even that won't submit a value). It works even if the url is set to #, and finally it gives a backup in case the user has disabled javascript (or the javascript doesn't work for some reason) they've still got a continue button available to click.

Related

Stop form from submitting without javascript

The problem is quite simple to understand but quite hard to execute. I am currently facing some clients that turn off their browser Javascript by default and this screw up my website a bit. Since my website send ajax requests on form submit, stop the form submit using Javascript, turning JS off means the form will be sent through and that's unexpectedly.
What I am trying to ask and achieve is whether it is possible to just using html purely to stop a form from submitting?
I think the best answer is; to have the original form action point to an error page, asking the user to turn on javascript.
Then let your javascript code fill in the form action parameter, once the ajax state is complete.
Alternatively or additionally, you could use a <noscript> tag as suggested in the comments, to generate a message on the original page.
I think you can simply change your submit button tag to an input and style it to look like a button and remove the type="submit" that's all. with out ajax it will not respond.

Form auto submit only once and reload same page

I have created a form in php which has to fetch data from table1 and dump it into table2 every time user clicks on a link (link provided in a different page). I have written code in a php page (assume eg -> test.php) including html as well. I tried submitting the form onload of the page using Javascript (document.formname.submit) but it keeps on going in an infinite loop and keeps inserting data in table2 again and again.
How do I prevent this and auto form submit only once and still stay on the same PHP (i.e. test.php) page, which also contains the code for displaying detail view of the inserted data in table2?
That's because simply calling submit() on a form fill cause a full page reload. If you want to keep the current approach, you should instead use AJAX call to submit the data from that form.
Read here for more details. The article explains how to do both GET and POST requests using JS.
That sad, your solution seems somewhat ... emm ... hairy. Why exactly are you copying data from no table top another?
Before JavaScript check this condition by using form name.
if ( ! isset($_POST['main']) )
Here main is form name.

How to update 2 forms with one submit button

I have 2 forms on my page that I'm looking to update with one submit button.
I am able to successfully update each form individually, however, I haven't been able to update them concurrently using the same button.
The first form is updated via the php code located on the same page (say page1.php) that I'm putting the button.
The second form is updated via redirection to another page (let's say page2.php) where an event is called/handled (after completion, the page redirects back to page1.php where the changes can be viewed) and I achieve this using the onclick="page2.php".
I was wondering how I should go about getting both of these forms to update when I click the button.
Code example:
<form id="form" method="post" action="page1.php">
<input type="submit" class="button" value="Submit" onclick="form.action=\'page2.php\';" />
</form>
Assuming by updating a form, you mean submitting, there is no way you can submit two forms at once since you can't have two redirections at the same time (it just won't make sense).
But, one of the options is to submit the first form via an AJAX call, and if the response is correct, do the normal submit of the other form. This also makes sense since you said that you're submitting the first form to the current page you're on, which means no layout changes, etc...
Ideally, you'd make a new landing page for the AJAX call (no need to render the whole page behind the curtains) which would just output the result of whatever you're doing there (for example, updating database, and if success, just echo 'ok'). Then just check if the response is the expected one ('ok' in the case above, though you might want to return some more info, like an id or something), and if so, submit the second form regularly.
Hope this wasn't too confusing.
The other method I can suggest is simpler, but involves changing the app flow.
You can try to combine the two forms into a single form and just submit it to page2. It's something worth thinking about, altough it might require a lot of rewriting of the existing code.

Acknowledgement on form submit

I want to show a acknowledgement (more precisely a popup) when form is successfully submitted.Previously I was using Ajax to validate form and display pop up but now I want to achieve same without Ajax.
Is there any event in javascript/Jquery which is invoked after successful form submission? or Is there any other alternative available?
Thanks!
EDIT 1 :
I am using Spring 3.0.
Here is the detailed scenario
1. User fill the form and click on submit
2. Request will be sent to controller (Server side)
3. Validation will be done at server side
4. If errors are present I am using Spring validation to show it and goto Step 1
5. else successfully submit the form and show a popup.
6. After user clicks on popup redirect to other page.
EDIT 2:
I am completely agree with the opinion that Ajax is the right/best way to do it and I already implemented it using Ajax. But client want to use non-ajax approach and I cannot go beyond his words.
This question piqued my curiosity, as I was trying to do something similar using the iframe solution suggested by Leon. Eventually I succeeded, however, I would like to suggest that rather than using a direct onload property, you make use of the jQuery .load() event on the iframe.
Edit: So here's how I set up the form (using HTML5, so quotes aren't necessary):
<div id=message></div> /* Example-specific, see below */
<form method=post action=backend.php target=iframe>
// Form data here
</form>
<iframe name=iframe></iframe>
I added the following CSS code to hide the iframe:
iframe {
border:0px;
height:0px;
visibility:hidden;
width:0px;
}
Don't use display:none, as some browsers will refuse to submit to an element that's not displayed.
Then in my $(document).ready() JavaScript...
$('iframe').load(function(){
// Your load event here.
});
You could also change that about, so that it specifically only triggers after a specific event (if you're using dynamic forms, for example). In such a case, you may want to use .unbind('load') before .load() to prevent previously-added .load() functions from calling.
Now when the form is submitted, it loads into the hidden iframe. When the iframe loads the page (backend.php, in my example), it triggers the .load() function. In my specific case, I set up a <div id=message> to display a message:
$('iframe').load(function(){
$('#message').html('The form successfully submitted.');
});
Without Ajax? No Problem - let's go back to how the Web really used to work in the past ;-)
Since I am getting you don't want to refresh the current page, how about this approach:
have a hidden iframe on the same page, with a name & id
point the target property of your form to the name given in the previous step
submitting the form will now be "hidden"
you can have an onload property on the iframe set to a javascript method of your liking to get called once the form finished submitting
that javascript code could also retrieve the contents of the iframe and check for your server-side response (maybe even including an error msg)
notify the user about the result
This is all fairly easy to setup, let us know how it works for ya..
I am not sure which language you are coding in.
One option - use javascript.
On the submit button onclick event (client side event), perform the page validation and display alert pop up, if the page is valid.
<script type="text/javascript">
function OnSubmitClientClick() {
Page_ClientValidate();
if (Page_IsValid) {
alert('Form has been successfully submitted.');
return true;
}
}
</script>
Why do you want to drop AJAX approach? Without AJAX, server side validation implies page reload. On page reload you would lose client side (JS) state.
One alternative is to use hidden frame/iframe/a new window to perform server side validation on form submit(possibly use the pop up you are referring to in your question). Which in my opinion is not the right approach(A BIG NO). You may rather stick to AJAX or go with non AJAX way of form submit.

Back Button Handle A Dynamic Form

I have a form with an array of text fields. The user (through javascript) can add an arbitrary number of text fields to the form. After submitting the form and pressing the back button the form displays only with the fields that were on the original form when it was first rendered (any added text fields are lost). What is the best way to allow the back button to render the form in the state when the user submitted it? Any ideas are welcome, some things I've tried are:
Put the form data in a cookie (this
doesn't work great for a couple
reasons but the biggest killer for me
is that cookies are limited to 4K in
size)
Put the form data in a session
Submit the form via AJAX and then manage the history
Thanks for the help. I've posted a test form on my website at http://fishtale.org/formtest/f1.php. Also here is a simple form exhibiting the behavior I mentioned:
<form action="f2.php" method="post">
<input type="text" name="text[]" id="text1"/>
<input type="submit" name="saveaction" value="submit form" />
</form>
Add Form Element
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js" ></script>
<script type="text/javascript" >
$('#add_element').click(function (event) {
event.preventDefault();
$('#text1').after('<input type="text" name="text[]" />');
});
</script>
This is similar to a question I posted a while ago, Best Way For Back Button To Leave Form Data, however, this form's elements are modified by the user.
How about creating an <input type="hidden"> (with no name or outside the form so it's not submitted) in which you store an encoded list of extra fields to add and their values? While the browser won't remember newly-added fields on ‘back’, it will remember the values of hidden fields that were in the form from the start.
Here's an example that saves the extra fields on document unload and retrieves them on ready:
<input type="hidden" id="remembertexts" />
<form action="http://www.google.com/" method="get">
<div id="texts">
<input type="text" name="text[]" value="" />
</div>
<div>
<input type="submit" />
<input type="button" id="addtext" value="+" />
</div>
</form>
<script type="text/javascript">
// Add new field on button press
//
$('#addtext').click(function() {
addInput('');
});
function addInput(text) {
$('#texts input').eq(0).clone().val(text).appendTo('#texts');
};
// Store dynamic values in hidden field on leaving
//
$(window).bind('beforeunload', function() {
var vals= [];
$('#texts input').each(function() {
vals.push(encodeURIComponent(this.value));
});
$('#remembertexts').val(vals.join(';'));
});
// Retrieve dynamic values on returning to page
//
$(function() {
var extratexts= $('#remembertexts').val().split(';').slice(1);
$.each(extratexts, function() {
addInput(decodeURIComponent(this));
});
});
</script>
Notes:
You can use form.onsubmit instead of window.onbeforeunload if you only need it to remember values over a submission. onunload doesn't work as some browsers will already have stored the old form values before that event occurs.
In Firefox the position of the hidden input is important. For some reason, if you put it below the dynamically-added fields, Firefox gets confused about which input it is and fails to remember the value.
This example doesn't work in Opera. It can be made to work in Opera, but it's a pain. Opera's calling of load and unload events is inconsistent so you have to use onsubmit instead, or setting the hidden field on a polling interval, or something. Worse, when Opera remembers previous form-field values, it actually doesn't fill them in until after onload has fired! This already causes many, many form-scripting problems. You can work around that by putting a small timeout in your onload to wait until the form values have gone in if you need Opera compatibility.
I can't find a prewritten library for this, but I'm sure its been solved before. If I had to it myself I would take this approach:
Use the command pattern so that each method which modifies the page's UI by adding controls also invokes an AJAX method to push the method invoked (textual Javascript representation) onto a queue stored in the server's session.
After body onLoad completes, use an AJAX method to query the server's session for a command queue for the page the user is on. If one is retrieved, just eval each member of the queue to rebuild the page's UI in the same order the user did it.
Keep in mind with this approach you are recording not just additions of controls, but removals as well. You will require separate state holders for user input controls, like text boxes (you will also likely need server-side session with AJAX method access).
In good browsers you can have it working perfectly simply by not breaking it.
Firefox 1.5 uses in-memory caching for entire Web pages, including their JavaScript states, for a single browser session. Going backward and forward between visited pages requires no page loading and the JavaScript states are preserved. source
This is supported in Opera and WebKit too. However DOM cache is only possible in you stick to the rules:
Don't use onunload, onbeforeunload.
Don't use Cache-control: no-store or must-revalidate.
In PHP you must change session.cache_limiter from patently_ridiculous (I think they spell it nocache) to none.
session_cache_limiter('none');
Unfortunately HTTPS is also out.
If you don't force browsers to reload the page, they won't. They'll keep the DOM and its values unchanged, exactly as RFC 2616 suggests.
However, if you're looking for place to stash the data, there's incredibly clever hack – window.name can store megabytes of data. It's not sent to server, and it isn't shared between windows.
There are also Flash cookies and HTML 5 localStorage is implemented in IE8 and Safari 4.
Step 2: The script processing the form puts the values entered into an array and stores that array into a session variable (or text / db / whatever you find appropriate).
Step 1: The script which outputs the form adds a javascript (which in turn fills in the form) if that session variable is found (and it also clears the session variable).
You could make your own back button at the top of the web page and make it bigger and prettier than the standard web browser back button.
Under the hood your code could know what the previous state was and revert to it or if there was no previous state you can maybe call the browser's back function?
Block the use of the back button. When the back button is pressed, rerender the previous page for the user with the new fields included, either visibly if that makes sense, or hidden. That way the user is able to use the back button normally and you have full control over the appearance of the ''previous'' page.
In your specific use case, you just need to render the page with all the fields visible and filled in with the values that were submitted.
This is a good pattern to follow for any wizard type of process where you provide a sequence of forms for the user to fill in and they may choose to go back to a previous form.
To make it perfectly clear, I am suggesting that you use this advice on capturing the onUnload event to trigger form submission (so that you get the entered values) and to rerender the previous page that "back" would have displayed (without the values). The only alternative is to use Ajax to send the entered values every time that the user leaves a field, and then have every page check with the server via AJAX to retrieve additional values to display.
Here are some additional pages that discuss taking control over the function of the back button and using the unload event to persist forms data:
Mastering the Back Button with Javascript
Don't Let the Door Hit You
Cross Browser unload Event and the Back Button
Persisting portlet forms data in WebSphere Portal V5.1

Categories