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.
Related
The id's #switchtopagetwo and #switchtoindex are assigned to buttons that do what you can infer from the id's names. What I want to do is on click of the button, I want to redirect to the new page via window.location = url; and then run a function that renders some data on the page via pagetwoData() or pageoneData(), depending on where I am at the moment.
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
pagetwoData();
});
//pagetwo.html button
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
pageoneData();
});
When I comment out window.location, the functions run and I can see the data on the screen, but there's no page redirect even on clicking the button. When I click on the buttons fast enough, I can see the function's data being rendered for a split second and then disappearing. When I console.log certain items, I can see the console.log's appearing in the console and then disappearing the same way.
Clearly there is an issue with window.location. Is there better code I can use for clicking the button, redirecting the page to load the page-2 data, then clicking the button again to go back to page-1 data?
When you redirect to a new page, the entire page context is abandoned and replaced by the new page. Nothing which happens on the source page after that redirect can be relied upon to still happen. But anything on the target page that's loading will happen.
Instead of trying to get Page1 to tell Page2 to do something when it loads, just have that something happen on Page2. For example:
// on index.html
pageoneData();
$('#switchtopagetwo').on('click', function () {
window.location = 'pagetwo.html';
});
// on pagetwo.html
pagetwoData();
$('#switchtoindex').on('click', function () {
window.location = 'index.html';
});
Basically, for any given page, whatever you want to happen on that page when it loads should be executed on that page when it loads.
I know this has been asked multiple times on here, but I would like some input.
The web app I'm working on displays a table from a database via Freemarker. It includes a submit button to delete entries from that database. The button works fine for sending requests, but I wanted to have it automatically refresh the page, to show the new table without that entry. I tried this:
<form onsubmit="location.reload()" method="post" action="http://localhost:8080/person/delete/${profile.id};">
<input type="submit" value="Delete"></form>
and this:
<form onsubmit="location.reload()" method="post" action="http://localhost:8080/person/delete/${profile.id};">
<input type="submit" value="Delete"></form>
Neither had any affect. Further research showed me that reload() will refresh the page from the cache, unless forceGet is set to true. I did this for both methods, and saw no difference. Then I thought that it was a case of the page refreshing before it could get the updated information from the server, so I had it wait 100 ms:
<script>
function reloadPage() {
setTimeout(function () {
location.reload();
}, 100)
}
</script>
<form onsubmit="reloadPage()" method="post" action="http://localhost:8080/person/delete/${profile.id};">
<input type="submit" value="Delete"></form>
This works, but I'd like to know if there is any insight on why the original methods wouldn't work. Also, are there any suggestions on alternatives to my code?
Edit:
To clarify, the path http://localhost:8080/person/delete/${profile.id}; doesn't lead to a page; its meant to call the method in the method in the resource class that will run the delete method:
#POST
#Path("/delete/{id}")
public void deleteProfile(#PathParam("id") int id) {
manager.deleteProfile(id);
}
Because onsubmit is called BEFORE the action is ran. The flow is this one:
Submit form
Call onSubmit events
Run action if event is not prevented
So what is happening is this:
Submit form
Reload page
Action is never reached because you are reloading the page, hence stopping all the page logic. Is like closing a program and opening it again.
Your 100ms is a dirty workaround because altough it works for you, it may not work for anyone that cannot process the action before those 100ms. Imagine a slow device, slow network or slow something that will delay the action more than 100ms. It will reload the page before the action is ran.
What I don't understand is why don't you let the webpage do the reload for you. Natural form submits takes you to the action url, loading it, hence reloading the page if is the same URL.
I'm not sure why your code works, it shouldn't. When submitting a form it will actually redirect you to the URL you specified in action, so reloading and redirecting at the same time is just not possible.
My suggestion is using a http request to delete the data. That would look like this:
<script>
function deleteData(var id) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
location.reload(); // request successfull, so reload
}
xmlHttp.open( "GET", "http://localhost:8080/person/delete/"+id, true );
xmlHttp.send( null );
}
</script>
<button onclick="deleteData(${profile.id})">Delete</button>
Alternatively you can use your form (without the reloadPage()) and have the page at http://localhost:8080/person/delete/xy redirect back to this site.
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.
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/
I'm using greasemonkey to manipulate a form on an existing web page. (autofill)
The action attribute of the form is itself, once submitted it prints a success message above the submit button.
What I'm trying to do is, once the form is submitted - I want to redirect the browser to another page. But this doesnt work with greasemonkey. Nothing happens.
I wrote a code to detect when the page is submitted, but doesnt work after the form is submitted.
getData("goingback"); //pulls the goingback data from database using ajax
if (goingback == "yes") {
window.location = "index.php";
} else {
//business as usual
// manipulate the form and get it ready for submission
sendPost("goback","yes"); // this function sends data to a php to be handled via ajax
//ajax stores the data in database
//the form is submitted using a timer and .click();
var submission = Math.floor(Math.random() * 10000) + 5000;
setTimeout(function() {
$('button[value="submit"]:first').click();
}, submission);
}
How can I achieve this?
Thanks in advance
The question is not clear; we might need to see the actual page itself. But, it sounds like the page is submitting the form via AJAX, and not a full post.
In that case, your script won't refire. Instead, monitor the page for the success message. Here's one way:
Suppose the success message is like this:
<div id="post_status">
<h2>Some one set us up the (data) bomb!</h2>
</div>
where the <h2> is added after the form posts.
Then this code will redirect after the post happens:
var postChkTimer = setInterval (checkForPostDoneNode, 200);
function checkForPostDoneNode () {
var postDoneNode = $("#post_status h2");
if (postDoneNode.length) {
window.location.assign ("index.php");
}
}
There is no need for that getData("goingback") or
sendPost("goback","yes"). Also that looks like it's setting goback but checking goingback -- which could be a problem. Although it is not the problem causing the behavior as described in the question.