Javascript code not running after the page is refreshed or reloaded - javascript

I have a javascript code that, whenever a checkbox is checked, will reload my current page and then is supposed to grey out some input fields.
However, it is only doing the reload when the page is reloaded the input fields are never greyed out.
$(document).ready(function(){
$("#storePickUp").on("click", function () {
if ($(this).is(":checked")) {
document.getElementById("shippingForm").submit();
document.getElementById("shippingAdress").disabled = true;
document.getElementById("shippingState").disabled = true;
document.getElementById("shippingCity").disabled = true;
document.getElementById("shippingZip").disabled = true;
document.getElementById("shippingZipCode").disabled = true;
document.getElementById("shippingButton").disabled = true;
}
});
});

So in your code on the 4th line where you call .submit()... unless you have some extra magic on the page that you are not showing, this line will proceed to post/get your form to whatever url you have configured in that form.
What this means is that the lines underneath that do not matter at all, since they will not be executed on the forms target page.
To get around this if you truly need the form post in the middle, you would need to post to a specific url and use that url as a trigger on page load to disable those elements. Not directly after the click, but rather on the newly loaded page that is the target of the form... make sense?

I think that's because it's only disabling them when you click on #storePickUp but if your page is reloaded it will reset.

Method submit is executed, page reloads, code after submit is never executed. Even if that code would be executed, page refresh nullifies any changes.
You should probably do submitting with ajax, not with submit method. If you are using jQuery, it will make it easy for you:
http://api.jquery.com/category/ajax/

Related

page reloads on chrome extension message send?

So I'm running a data collection project by injecting a html form into a third party website, via a chrome extension, which instructs users to describe the data they see and submit it to my server.
For some bizarre reason, however, whenever the user clicks the "submit" button to send the form contents to the background page (and from thence to the server), the underlying page reloads, and, not only that, but it reloads with the contents of the form I injected showing up in the url after reload. Which is kind of bizarre behavior.
I don't know if this is something in my code, or even if it's something in the underlying web page's code (maybe it redefines chrome.runtime.sendMessage or something as some kind of anti-extension technique?!!?). I'd really like to stop this behavior if possible... does anyone have any ideas?
The relevant parts of my code, stripped down a little:
var cururl = window.location.href
var codestring= "[A HTML FORM TO INJECT]"
var raformvalues = {};
function codeValues() {
$.each($('#mainCoding').serializeArray(), function(i, field) {
raformvalues[field.name] = field.value;
});
}
function sendValues() {
let pageinfo = {"page": document.documentElement.outerHTML,
"url": cururl,
"title": document.title,
"timestamp": String(Date.now())};
let tosend = $.extend({"type": "doctype"}, pageinfo, raformvalues);
chrome.runtime.sendMessage(tosend);
chrome.storage.local.set({'lasturl': pageinfo.url});
$("#pgcodediv").empty();
location.href = cururl; // note: I added this line to try to stop the reloading and url/changing behavior. behavior is the same with and without it.
}
function appendCodingInfo() {
$("#headerID").append(codestring);
$( ":checkbox, :radio" ).click( codeValues );
$( ":text" ).change( codeValues );
$( "#codingsubmit" ).click(sendValues);
}
appendCodingInfo()
when the user hits the submit button (#codingsubmit, of course), the message gets passed and the background page handles it correctly, but the page refreshes unbidden, and the contents of raformvalues show up in the URL of the refreshed page (i.e., when I call window.location.href from the console the contents of that object show up as parameters to a get request, i.e., http://url?prop=value&prop2=value2 -- no clue why.
If you click a button with type="submit" in a form, by default browser will reload the page after the form is submitted.
To prevent the page reloaded, either replace type="submit" with type="button" or call e.preventDefault() inside sendValues handler.
Appendix:
According to MDN, the default value for button is submit.
type
The type of the button. Possible values are:
submit: The button submits the form data to the server. This is the default if the attribute is not specified, or if the attribute is dynamically changed to an empty or invalid value.
reset: The button resets all the controls to their initial values.
button: The button has no default behavior. It can have client-side scripts associated with the element's events, which are triggered when the events occur.
menu: The button opens a popup menu defined via its designated element.

location.reload(), Javascript,HTML

I'm having a problem always when I try to use the following code in a button in my HTML file.
onClick=window.location.reload();
mapGenerator();
The page reloads but the javascript (mapGenerator) that make a D3JS view doesn't appear. What am I doing wrong?
location.reload() will immediately reload the page and prevent any following code to execute.
You can, however, create a function that executes your method after the page has (re)loaded:
window.onload = function() {
mapGenerator();
};
This method will run every time the page has fully loaded. To only run the code after you have reloaded the page using location.reload(), you could create a method that handles the click by setting a cookie and then reloading the page.
function handleClick() {
document.cookie="reload=true";
location.reload();
}
This would require you to change your onClick value to onClick="handleClick();". Now, whenever the page loads, you can check whether the cookie has been set. Your window.onload function now changes to this:
window.onload = function() {
if(document.cookie.indexOf("reload") >= 0) {
mapGenerator();
}
}
Checking if a cookie exists - answer by Michael Berkowski
After the reload it's up to you whether you want to unset the cookie — if you don't, the page will run the function mapGenerator on every page load until the cookie expires.
If you need more help with cookies, check out W3Schools' tutorial.
As per your description mentioned above two actions are to be taken on click. As the first action reloads the page the second action is lost. If you want any action to be taken on load of the page, mention the same on onload event of the page.

prevent multiple submission with button

I am currently viewing all the possibilities for preventing multiple submission with button tag. The problem I am facing is that if users click submit button really fast it will enable them to submit multiple posts. I would like to restrict the submission to just one submission. I tried to use onclick="this.disabled = true, but it makes the button not working at all. The current button tag looks like this:
return "<button class='button btn btn-primary' id='gform_submit_button' onclick='this.disabled = true' type='submit'><span>Submit!/span></button>";
Can anyone guide me as to how to achieve this?
Ultimately, you cannot prevent multiple submissions on the client-side. You would have to implement these security measures on the server-side, in whatever server-side language you are using (e.g., PHP).
On the client side, you could do something like this
var canSubmit = true;
$('.button').click(function(){
if(canSubmit)
{
// fire missiles
canSubmit = false;
}
else
{
// sorry missiles loading
}
});
Now since after clicking once canSubmit has been set to false, a second click would not run the code. After validating or processing your submitted data you can set canSubmit back to true.
When the button is onClicked call this function:
function submitFunc(formId){. document.getElementById(formId).submit();
}
Submitting a page is always going to be tricky. There are two challenges with submit
As you rightly mentioned that user can submit same page multiple times
After submitting page if user refresh the page then also page is going to be resubmitted
There is one trick to handle this challenge redirect the page with GET call. The GET call which you have used to load the data. Read more about it here.
So I would recommend to redirect page to GET once form is submitted.
In this process the new form will be loaded and if user try to submit the form validations will be fired that will handle 1st challenge.
And due to redirect as your last call is GET on refresh data will be loaded and there is no harm in it.

How to check page is reloading or refreshing using jquery or javascript?

I have to do some kind of operation on the page refresh or reload. that is when I hit next page or Filter or refresh on the grid. I need to show some confirmation box over this Events.
is there any event which can tell you page is doing filer? refresh or paging? using javascript?
Thanks
If it is refreshing (or the user is leaving the website/closing the browser), window.onunload will fire.
// From MDN
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
https://developer.mozilla.org/en/DOM/window.onunload
If you just want a confirmation box to allow them to stay, use this:
window.onbeforeunload = function() {
return "Are you sure you want to navigate away?";
}
You can create a hidden field and set its value on first page load. When the page is loaded again, you can check the hidden field. If it's empty then the page is loaded for the first time, else it's refreshed. Some thing like this:
HTML
<body onLoad="CheckPageLoad();">
<input type="hidden" name="visit" id="visit" value="" />
</body>
JS
function CheckPageLoad() {
if (document.getElementById("visit").value == "") {
// This is a fresh page load
document.getElementById("visit").value = "1";
}
else {
// This is a page refresh
}
}​
There are some clarification notes on wrestling with this I think are critical.
First, the refresh/hidden field system works on the beginning of the new page copy and after, not on leaving the first page copy.
From my research of this method and a few others, there is no way, primarily due to privacy standards, to detect a refresh of a page during unload or earlier. only after the load of the new page and later.
I had a similar issue request, but basically it was terminate session on exit of page, and while looking through that, found that a browser treats a reload/refresh as two distinct pieces:
close the current window (fires onbeforeunload and onunload js events).
request the page as if you never had it. Session on server of course has no issue, but no querystring changes/added values to the page's last used url.
These happen in just that order as well. Only a custom or non standard browser will behave differently.
$(function () {
if (performance.navigation.type == 1) {
yourFunction();
}
});
More about PerformanceNavigation object returned by performance.navigation

auto fill form and submit

I have a form on my 404 page that is auto filled with the address the user tried to find. I also have javascript that then auto submits that form.
The problem is, once it auto submits it keeps looping and the page keeps reloading.
I am trying to wright the javascript code to fire once and then stop.
The script fires on page load so that's whats causing the loop.
Outcome: I need it to fire on page load, page reloads, the code checks to see if its already reloaded once then stops.
For my test I am trying to make it pop an alert that says "I reloaded once" just so I know its worked.
This is my code so far
<script type="text/javascript">
window.onload = function() {
var grabedurl = window.location.href
document.getElementById('badurl').value=grabedurl;
if( history.previous != history.current ){alert('I reloaded once')}
else
setTimeout("document.getElementById('errorsubmit').click()", 3000);}
</script>
What you can do is add the state of the page already having been reloaded or not to the query string part of the URL. This should be done in your form's action, e.g. action="?submitted"
window.onload = function()
{
var form = document.getElementById("aspnetForm");
form.setAttribute("action", form.getAttribute("action") + "&submitted");
var grabedurl = window.location.href;
document.getElementById('badurl').value = grabedurl;
if (/submitted/.test(window.location.search.substring(1)))
{
alert('I reloaded once');
}
else
{
setTimeout("document.getElementById('errorsubmit').click()", 3000);
}
}
However, you might want to consider alternative approaches -- such as submitting the form via an XMLHttpRequest; having another, separate action page to submit the form to, or having the server log the request.

Categories