I have more than six functions like the following retrieving data to html page via server and update html which continues to run all the time when the web page is viewed. The Issue I'm having is after a while the web page pops up a warning as,
Alert Popup Warning in Firefox
A script on this page may be busy, or it may have stopped responding.
You can stop the script now, or you can continue to see if the script
will complete.
Script: "http://../javax.faces.resource/jquery-1.7.2.js?ln=js:3983"
After getting this warning the web page functionality gets unresponsive, Is there a solution to this problem? Is it because of a issue in the way I have coded? Why is it pointing to jquery library?
Code:
function myDatapoll(){
$.ajax({
type : "GET",
url : '../jsonData/',
dataType : "json",
async : true,
cache : false,
success: function(data) {
if(data!=null){
if($("span[id='accBal-"+data.pID+"']").length>0){
$("span[id='accBal-"+data.pID+"']").text(parseFloat(data.accBal).toFixed(2));
}else{
$("#cash").html('<span id="accBal-'+data.pID+'">'+parseFloat(data.accBal).toFixed(2)+'</span>');
}
}
setTimeout('myDatapoll()',1000);
},
error : function() {
}
});
}
Just a shot: put a setInterval outside your function instead of the setTimeout:
setInterval('myDatapoll()',1000);
function myDatapoll(){
//same as before but remove the setTimeout
}
Do not use setInterval in this case. Using setInterval, myDatapoll() executes every 1000 ms regardless the request is complete or not. It will only add to the trouble. The setTimeout approach you have implemented is the right way to do it. I am not sure why you are getting that exception in Firefox.
Are you sure about the dataType? You are requesting a xhtml file and the data type is set to "json"?
Related
So, I'm having a bit of an issue in HtmlUnit
I'm trying to run a bit of Javascript on Facebook's message page to send someone a message. The JavaScript I'm using is this, and it runs just fine in the browser's console:
document.getElementsByName("message_body")[0].value = "test"; var e = document.createEvent('KeyboardEvent'); e.initKeyEvent('keydown', true, true, window, false, false, false, false, 13, 0); document.getElementsByName("message_body")[0].dispatchEvent(e);
It first selects the message body textarea by its name, types in "test", and then presses the enter key, sending the message.
When trying to use the executeJavaScript() in HtmlUnit method it fails, but not even because of my code.
I'm receiving this error:
net.sourceforge.htmlunit.corejs.javascript.EvaluatorException: Java class "com.gargoylesoftware.htmlunit.ScriptException" has no public instance field or method named "message". (https://fbstatic-a.akamaihd.net/rsrc.php/v2/yj/r/zt0nwbhPchP.js#36)
...which appears to be an error in Facebook's JavaScript, not mine.
The problem? I can't run any of my own JavaScript on the page without HtmlUnit seeing Facebook's code and breaking with an exception.
Is there any way I could circumvent this? Also, if the script works perfectly fine in the browser, why would it break HtmlUnit?
Thanks!
ok, so the question is two years old, but in my case if I set
webClient.getOptions().setThrowExceptionOnScriptError(false)
I can work around it.
Recently I am working on a project which using ajax to call java servlet, and the request takes more than 10 sec to get the response, so I need to make sure during this time user won't be able to submit the form again, and my current approach is detect submit button click event and disable submit button, once success or error function is triggered in ajax, enable the button again, but this is not a good approach.
---- Edit ----
Sorry, I wasn't explain clearly, what I mean is this can stop non technical background user, but if any one intend to attack the site or whatever reason,
they can simply modify html code to enable the button, and do another submit,
Before I tried another way which set a cookie interval after form submit, and check the cookie when request finish, but just wondering whether there is any other way to do this, this question is purely for learning purpose.
Sorry for my English:)
I dont see anything wrong with disabling the button, that is what I frequently use, because this not only provides an indication that the system acknowledged your click but also prevent the user from clicking again.
If for some reason you dont like that you can disable the underlying method call something like this:
var isSubmitting = false;
function handleClick(){
if (!isSubmitting)
{
isSubmitting = true;
$.ajax(
"http://yourservice/submit" {
data: {someData:123},
contentType: 'application/json',
type: 'POST',
success: function(){
isSubmitting = false;
},
});
}
}
About your edit, the cookie sounds like a good approach, basically you need something that the server is going to pass to the client, and then check on submit. once that has been authorized the server will prevent processing of further requests with the same parameter.
But bear in mind that a malicious user would spawn thousands of requests to get cookies and then perform all the submissions anyway, so it is not really a defence against attackers, for that you would have to implement some form of throttling.
So in the end if you just want to prevent accidental submissions the button hide will suffice.
Something I have done and has been successful is a combination of what you described and preventing the function called by the button to execute twice. I do this by keeping a variable that gets set to true with the first request, then on subsequent request I check for it, if it's true, I don't do anything. Something like this:
var isRequestAlive = false;
var submit = function(){
if(!isRequestAlive){
isRequestAlive = true;
doAjaxStuff("", function(){
isRequestAlive = false;
})
}
}
well I'm doing a web application, which processes a file after it's done uploading and I want somehow the user to to be able to get some info about the progress. Now I was thinking of creating a jsp progress page, which would sleep for 5 seconds, then generate a request and supply it with the filename that we want to know the progress of. So how do I do this, or is there a better way? Maybe JavaScript can do the desired actions? So what would you guys suggest? Thanks.
You need to poll the server using ajax. If you're using Java, the Apache FileUpload library has an interface called ProgressListener, which you implement to determine the upload's progress. You can track percentage received or just mark a file complete when it's complete. On the client side, you check the progress every few seconds until you see it's finished. Also, if you want your user to appear to remain on the same page, try setting the target attribute of your form to the id of a 0x0 iframe on submit.
If you decide to code the javascript, a simple polling function might look like this:
function poll(uploadId) {
$.ajax({
url: '/path/to/upload/status/servlet',
type: 'POST',
data: 'id=' uploadId,
dataType: 'json',
timeout: 10000,
error: function(err){
// handle error
},
success: function(data) {
var status = data["status"];
if (status == 'finished')
{
// completed upload logic
}
else
{
setTimeout(function() {
poll(uploadId);
}, pollingIntervalInMillis);
}
}
});
}
Poll the server (requires a progress API) periodically (via javascript) for the processing status and update the page accordingly when you get a positive result.
I would like to implement a page that be displayed to the user whilst a system command is run. As soon as the command completes the user should be routed to another page.
What are some strategies to implement this?
(A solution without javascript would be ideal)
It can definitely be done. You want to look at Asynchronous programming with HTTP in the documentation, it explains how to do this in a non-blocking way. You will need a little bit of javascript for the redirecting part though.
And I don't know what you mean with "system command" but you probably want to create a job for it, so you can trigger it with a request. You can then poll it until it's finished and then redirect the user. But really the documentation does an infinitely better job at explaining it then I'm doing now.
Here's an example of a controller action where I assume your system command returns some kind of String output for the user. When the Job is completed it will sent a response to the user, thus triggering the success handler in the javascript example.
public static void executeSystemCommand(String input) {
Promise<String> outputPromise = new SystemCommandJob(input).now();
String output = await(outputPromise);
renderText(output);
}
Basically if you're using jQuery's $.ajax you can use the complete event to poll the data (just do the request again if it didn't succeed within the timeout time) and use the success/done event to redirect the user when the application responds to indicate that the "system command" is done running.
Example of a function you could use:
function poll(){
$.ajax({
url: "/systemcommand",
success: function(data){
// redirect to next page here
document.location.href = '/output'
},
complete: poll,
timeout: 20000
});
};
There is also a great example on long polling in javascript on StackOverflow.
I had the following:
Link 1
but I noticed that the javascript function CreatePageView() did not get executed all the time and was creating a race situation. Sometimes the javascript would get executed, others times the redirect was happening first.
So I wanted to control the order of events and thought to invoke the servlet within my javascript function.
function CreatePageView()
{
//Execute javascript function here
//Invoke servlet here
document.forms[0].action = "/servlet/MyServlet";
document.forms[0].submit();
}
When I invoke my servlet, my session gets destroyed and I get redirected to the login page. Can anyone explain why this is happening? Or perhaps suggest an alternate method of invoking the servlet without killing the session? Thanks in advance.
This sounds much like as if that JavaScript is firing an asynchronous request. Otherwise the problem doesn't make any sense. The link's action will in any way only be executed when the JavaScript function has returned. But when you're firing an asynchronous/ajaxical request in the JS function, then indeed a race condition may occur. It namely doesn't execute in sync. It executes "in the background".
You need to ensure that the link is only invoked when the asynchronous request is finished. Assuming that you're doing it in "plain vanilla" JS by XMLHttpRequest instead of a convenient Ajaxical JS library like jQuery, then you need to do the job in the onreadystatechange.
Change the link as follows:
<a href="/servlets/MyServlet" onclick="return createPageView(this)">
(note that the javascript: pseudoprotocol is unnecessary and that JS functions usually start with lowercase)
And fix your JS function as follows (not MSIE compatible, fix that yourself)
function createPageView(link) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
window.location = link.href; // See?
}
}
xhr.open('GET', 'http://example.com', true);
xhr.send(null);
return false; // Block link's default action.
}
As to the question why the session get destroyed, it will be "destroyed" when the request headers doesn't contain the proper session cookie, or when you call session.invalidate() in server side, or when the request is been fired on a different domain/context. You're the only one who can investigate which one is the culprit.