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.
Related
I have a form with a slider with which somebody can rate a picture. The form should be submitted when the slider is dragged, so "onmousup". This works fine. However, the page should be refreshed so that the rating that the user did is already submitted. This all happens on the index page so that location where the user scrolled to, should not be lost.
I tried to make the slider like this:
<%= f.range_field :score, class:"form-control-range slider", id:"formControlRange", onMouseUp:"submit(); reload(); " %>
...
<script>
function reload() {
console.log("hi");
location.reload;
}
</script>
This way I hoped that when the onMouseUp event happens, the page is first submitted and the page then reloaded, so that the rating the user did is displayed. If I have the slider without the "reload()" function then the form is submitted, but I have to reload manually so that the changes can be displayed.
Somehow, calling having the slider like this doesnt make both functions happen. Only the function that is called first is executed.
I have seen in other threads that having the slider like onMouseUp:"submit() && reload()", but this also doesnt work for me...
Do you have a way to make this work? Or do you have an idea of how the reload thing would be done better.
Thank you so much for your help!
Vincent
UPDATE:
I have looked up a different way, and it actually works when I set a timer for the reload function like this:
function reload() {
console.log("hi");
setTimeout(function()
{
location.reload(); //Refresh page
}, 50);
}
Funny thing now is that it works 50 ms, but not with 5 ms. This points to that it is somehow related with the order. Does anybody know how to tell the code to only reload the page AFTER the form has been submitted?
location.reload is a function, you need to call it as a function:
function reload() {
console.log("hi");
location.reload();
}
But this will not fix the problem by itself, because you are doing a submit and then reload. What if the reload is faster than the operation performed on submit? Then your old state is reloaded. What if the submit operation fails?
If we assume that you keep your current approach, then you need to do the submit and synchronize in some way before you reload (or rerender). If there is an error, display an error.
You can do this with AJAX. Or, if you prefer post and submit, then your server could resend the output as a response to post, which is pretty well handled by the browsers.
I personally prefer to do an AJAX request, handle the response and refresh the parts of the UI that are to be changed.
EDIT
This is how AJAX request can be sent:
function sendRequest(type, url, callback, async, params) {
if (async !== false) async = true;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = callback;
xhttp.open(type, url, async);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
call this function, like:
sendRequest("POST", "yoururl", reload, true, yourparams);
Where reload is your function modified as above and yourparams is a set of parameters, like "firstparam=firstvalue&secondparam=secondvalue".
You've typed location.reload, missing () to call a method.
Please post the code of submit() function.
I have a webpage that makes a POST request to a PHP script. Depending on the result of the request, the onclick event for a button sets a redirect to one of two pages.
<button id="button" type="submit">Proceed</button>
...
$.post('script.php', {
key: value
}, function(result) {
if (result != null) {
document.getElementById("button").onclick = function() {
window.top.location.href = "https://example.com/page?otherkey=othervalue";
}
} else {
document.getElementById("button").onclick = function() {
window.top.location.href = "https://example.com/otherpage?otherkey=othervalue";
};
}
});
This works fine on desktop browsers, but on Safari on iOS (specifically tested on iOS 10.3.2) upon clicking the button, the page refreshes and doesn't redirect to the correct site. In addition, it clears any URL parameters that were previously there. So for example if the page with the button is example.com/page?key=value, the page will refresh and become example.com/page?#_=_. I've tried debugging and checking a Javascript console, but it doesn't say anything.
The redirect is a page in my own domain, though the page with the button is integrated into a Facebook app page, if that's relevant.
Also, if I construct the URL on my own and try to go to it normally, it loads fine. I don't know what could cause this, so I'm not sure if there's any other relevant information worth posting, but I can say more if necessary.
Safari does not deal well with return false being done in the function, and especially with no return at all. I would include a onsubmit="return function();" in the html element, which I'm guessing is a form. You also attach this to the submit() event listener via $('[the form ID]').submit(function(){ do something here; return false;});
I was right that I suppose I didn't supply enough detail, but it seems that because the button in question was inside a <form> tag and acting as a submit button, that was messing it up. To solve the issue, I removed the form (since I was not submitting any data anywhere, just using the button to redirect the page) and it solved the issue. Now it works on desktop and mobile browsers.
Im trying to track when a user hits the submit button on a contact form.
The page's URL doesn't change, its static.
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
Do I need to edit my analytics account?
Where do I add the additional javascript?
UA is installed correctly (analytics.js)
I'm new to GA and javascript so please break it down for me.
Thanks
I can't track a differnt URL after submission, the only option would be to track when a user hits the submit button.
That is a bit of a non sequitur. Even when the Url does not change there is probably some stuff happening - before you send it there is probably some form validation, and there is some action behind the scene to send there form, like e.g an ajax call.
You could attach event tracking to a submit handler:
<form onSubmit="ga('send','event','category','action','label')">
<input type="text" id="text" name="text">
<input type="submit">
</form>
However this would just tell you that somebody hit the submit button, not if they filled in the form correctly or if the form actually has been sent.
Now I enter speculation land, because I do not know how your form actually works - maybe you can show us an url or give more information.
But maybe you have a validation function that is called on the submit action of the form to see if the form is filled in correctly. In that case it would be advisable to do the tracking in the validation function (horribly simplified example, not production code):
<form onSubmit="validate()"><input type="text" id="text" name="text"><input type="submit"></form>
<script>
function validate() {
var test = document.querySelector('#text').value
if(test = "") {
ga('send','event','Form','Submit','Submitted, but not filled in');
return false;
}
ga('send','event','Form','Submit','Submitted with correct values');
return true;
}
</script>
That's a tad better, at least it tracks the difference between correct submissions and invalid submissions.
Even more speculation: If your form is sent without page reloads it uses probably an ajax call, and there is a huge probability that is uses jQuery (I say that because a) it really is probable and b) it's easier to construct an example in jQuery. The same can be achivied with other libraries or in native JS, but the example will produce an error if you do not use jQuery).
jQuery has a thing called "global ajax handlers". "Global" means they are not callbacks for a specific action, they hook into jQuerys ajax "mechanism" whenever a call to an ajax function is made. The following might work if you have only one aja event per page (else you need logic to distinguish the different ajax event e.g, by checking the url they are being send to), and allows you to track if the ajax call has returned successfully, like when your form data has been send to the server and the request return a 2xx status code:
$(document).ajaxSuccess(function() {
ga('send','event','Form','Submit','Yeah, form data sent to the server');
});
However this does not tell you if the data has been processed correctly. For that you need to make the server emit a success message and check the response:
$( document ).ajaxSuccess(function( event, xhr, settings ) {
if ( settings.url == "formprocessor.php" ) {
if(xhr.responseText.indexOf("success") > -1) {
ga('send','event','Form','Response Received','Form data processed ');
} else {
ga('send','event','Form','Response Received','Form data NOT processed ');
}
}
});
The global ajax event handler is attached to the document - you can put that anywhere on your page, it will do nothing unless an ajax event was called.
Again, this is not production code. Do not try to copy and paste.
This was certainly a bit much if you are new to this, but it should at least help you to improve the question and to see what kind of things are possible. If you can share an Url to your form I can possibly improve the answer.
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.
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.