My application uses polling to update the status of a music player. I'm using setInterval to make an Ajax call every half a second to do this. It works on many browsers (Chrome,Firefox, Safari... ) except the Nook color's browser. When the page loads it updates the correct information, but after that it always loads the same information. This was confirmed using alert. Here's the original code
function getStatus() {
request = new XMLHttpRequest();
request.open("GET", SOME_URL, true);
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200)
updateStatus(request.responseText);
};
request.send()
}
setInterval(getStatus, 500);
Any ideas why it is always loading the same info (the info it fetches initially) ?
Also: it only loads the most current information if you clear the cache. This Nook was rooted and also had Firefox and it would work just fine. It's the Nook native browser that is doing this (rooted or unrooted).
Internet Explorer has a weird quirk where it caches AJAX content. I imagine you are seeing the same issue in the Nook browser. The solution is to add a "cache buster" parameter, which is basically just a random parameter so the URL is treated freshly:
"SOME_URL?random=" + Math.random()
Related
I'm trying to run "inherited" code and since I'm fairly new to HTML & javascript I keep running into annoying little issues (that's how you learn :D ).
I have a GET request that is meant to load an mp4 file from a server, but for the sake of debugging and practice, I'm trying to load it from a local directory. I enabled the "--allow-file-access-from-files" flag on my chrome, so I know it's not a SOP issue. I can't figure out why, the request is sent 3 times, ALWAYS the first and last fail and the 2nd doesn't, but the file is not loaded.
here's a simplified version of the code:
var req = new XMLHttpRequest();
req.open('GET', currentFileName, true);
// currentFileName is an mp4 in the same directory
req.responseType = 'blob';
req.onload = function () {
// Onload is triggered even on 404
// so we need to check the status code
if (this.status === 200) {
console.log("success!");
doSomeFunc();
}
}
};
req.send();
here's the network log:
I looked into many possible solutions (example 1, 2, 3, 4, 5)
Couldn't find a question where this happens with local files.
What might be wrong?
I've searched the archives but not found anything specific to my query.
In JavaScript I have a function with a callback function that fires a request at a postcode API to get coordinates for a postcode.
const getPostCodeLatLng = (strPostCode, callback) => {
alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
const request = new XMLHttpRequest();
request.addEventListener('readystatechange', () => {
if(request.readyState == 4){
const jsnPostCode=JSON.parse(request.responseText);
callback(jsnPostCode);}});
request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
request.send();
};
and
getPostCodeLatLng(strInputFieldValue, (jsnPostCode) => { // use the function to get data about the postcode and callback to this function
if(jsnPostCode.status=="match"){
alert("used API"); // !!! DOESN'T ALERT ON MOBILE !!!
let strPostCodeLatLng = "LatLng(" + jsnPostCode.data.latitude + ", "
+ jsnPostCode.data.longitude + ")";
setFieldswithLatLng(strPostCodeLatLng);
objDisplayFindCons.value=`Postcode: ${strInputFieldValue}`;}
else objDisplayFindCons.value=`No match found for Postcode: ${strInputFieldValue}`;})
The functions work fine on a desktop but didn't work on either a Samsung phone nor tablet. I'm using Chrome on all devices.
The second section of code is part of a larger section that responds to an event where data is entered into a text box, validated as a possible postcode (using regex) and then requested as per the first function. The JSON text response is then parsed and checked to see if a match was found (the server returns valid JSON for unfound postcodes).
I am clear that it all works fine until it encounters the function call getPostCodeLatLng() where it never runs either of the alert("used API") statements on mobile.
I am new to JavaScript and finding coding callback functions and events challenging but I can't see any obvious bugs/reasons for this to fail on mobiles.
Are there known problems or limitations to what I'm doing?
Is there a way to workaround this or debug it effectively on mobile?
Please help!
Thanks,
Phil
So I tried various things and found the issue to be with using a http request.
Apparently from now on all requests from a Chrome browser on Android need to be https.
So changing request.open('GET', 'http://api.getthedata.com/postcode/' + strPostCode);
to request.open('GET', 'https://api.getthedata.com/postcode/' + strPostCode); fixed the problem straightaway.
Here is an article mentioning the change:-
https://www.thesslstore.com/blog/https-will-now-be-the-default-for-all-android-p-apps/
You live and learn...
I have a web project in PHP and it accesses a Java Project that uses the Restlet Framework. The web project is running on Apache and I am testing it using localhost. The Restlet Framework also uses localhost as the domain, but the url is slightly different: localhost:8888/
This is the Javascript that, using Ajax, makes a call to one of the Java classes (CollectionPublic) using the URL above.
var url = "<?php echo $config['restServer_url'] ?>collectionPublic";
var params= "pageList="+facebookPages+"&time="+time;
var client = new XMLHttpRequest();
client.open("POST", url,true);
client.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
client.onreadystatechange = function () {
if (client.readyState != 4) return;
if (client.status != 200 && client.status != 304) {
alert("error "+client.status);
} else {
alert("success");
}
callback(client);
}
if (client.readyState == 4) return;
client.send(params);
I have tested and the call is being made correctly, using the URL localhost:8888/collectionPublic, and it is reaching the CollectionPublic class (the class is working fine).
The PROBLEM is: When this call is made, the CollectionPublic class takes a long time to complete its task, and the user should be able to access other pages (on the same server) or reload the page. However, when either of these things happen, the alert("error "+client.status) pops up and the value of client.status is 0. The call is then aborted, but the CollectionPublic's task continue normally, and when it finishes, nothing happens in the web page (before, the alert("success") was being fired).
I spent hours trying to figure out what was causing the error, since this was working last week. Most of the posts I found said that it could be a Cross-Origin Resource problem, since localhost and localhost:8888 are not considered as the same domain. To see if that was really the problem, I started Chrome using the --disable-web-security argument (and it was really disabled) but the issue was still there.
The weirdest thing is that it has worked before, and I changed absolutely NOTHING in the code.
I have seen this post Reloading page while an Ajax request in progress gives empty response and status as zero and it seems quite similar to what I am facing.
Hopefully, I have made myself clear, but if you have any doubts regarding this issue, just ask.
Thanks a lot in advance.
I'm not convinced that the ajax request itself is quite right. if (client.readyState != 4) return; will always be true aside from when its actually 4. This may be better:
client.onreadystatechange = function () {
if(client.readyState < 4) {
//not complete yet
return;
}
if(client.status != 200 && client.status != 304) {
//an error
alert("error "+client.status);
return;
}
if(client.readyState === 4) {
//complete
callback(client);
}
}
As for the problem whereby the ajax call is aborted: This is correct behaviour. All XHR calls will be aborted by the browser as soon the page is reloaded or unloaded. Perhaps this was somehow not the case when viewing pages locally. I would not allow the user to navigate away (or reload) whilst the ajax in progress. As a work-around, your class could set a session variable that is read by your page.
I'm just wondering why this is not working with IE. It works fine with Chrome and Firefox.
window.onbeforeunload = function()
{
fetch("http://"+window.location.hostname+"/process_sc.php?cC=" + 1);
}
function fetch(url) {
var x = (window.ActiveXObject) ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest();
x.open("GET", url, false);
x.send(null);
}
How can you tell it isn't working?
In general, there's little time between beforeunload event, unload event and actual page exit. At page unload all running scripts are dropped (browser than closes the window or navigates to address provided by user for example).
What might be happening here is browser doesn't really have time to send ajax request before page is unloaded.
I've seen couple of ways to ensure your final request before page unload will be completed. One of them is sending request and then introducing loop that is running for X number of miliseconds, postponing unload event and ensuring ajax request can be completed.
window.onbeforeunload = function() {
fetch("http://"+window.location.hostname+"/process_sc.php?cC=" + 1);
// here we force browser to wait for 300 seconds before proceeding with unload
var t = Date.now() + 300;
while(Date.now() < t) {};
}
The problem is that you use a GET instead of a POST request. The browser may use a cached result from the very first request.
This explains the fact that "it works only on the first time I open IE" as written as in response to another answer.
By the way, the AJAX call in onunload seems to work reliably in IE10 only if you use the parameter async = false in XMLHttpRequest.open(...), which you already did.
I have a basic html page which has links that point to different site. What I want to do is track the clicks. I am doing so by sending a 0 pixel image call on Click event of the link without returning false on click event.
The same works fine on all the browsers except Safari(on windows OS).
when a link is clicked using javascript I delay the redirect and send an image request over to the server and log the click on server side. I have tried increasing the delay but with no success... The trackers work gr8 on all the browsers except Safari which does not sent the request at all.
I dont know why but possibly its that safari waits for the complete js to be executed before making the request and after the whole js is executed it gets redirected....
=========================================================
<html>
<head>
<script type="text/javascript">
function logEvent(){
image = new Image(1,1);
image.onLoad=function(){alert("Loaded");};
image.onLoad=function(){alert("Error");};
image.src='http://#path_to_logger_php#/log.php?'+Math.random(0, 1000) + '=' + Math.random(0, 1000);
pauseRedirect(500);
}
function pauseRedirect(millis){
var date = new Date();
var curDate = null;
do {curDate = new Date();}
while(curDate-date < millis);
}
</script>
</head>
<body>
Site 1<br/>
Site 2<br/>
</body>
</html>
=========================================================
Code works in chrome, firefox, ie and Opera. Does not work on Safari only..... any clues....
I had the same issue with all WebKit browsers. In all others you only need to do new Image().src = "url", and the browser will send the request even when navigating to a new page. WebKit will stop the request before it's sent when you navigate to a new page right after. Tried several hacks that inject the image to the document and even force a re-paint through img.clientHeight. I really don't want to use event.preventDefault, since that causes a lot of headaches when a link has target="_blank", form submit, etc. Ended up using a synchronous XmlHttpRequest for browsers supporting Cross Origin Resource Sharing, since it will send the request to the server even though you don't get to read the response. A synchronous request has the unfortunate side-effect of locking the UI-thread while waiting for response, so if the server is slow the page/browser will lock up until it receives a response.
var supportsCrossOriginResourceSharing = (typeof XMLHttpRequest != "undefined" && "withCredentials" in new XMLHttpRequest());
function logEvent() {
var trackUrl = 'http://#path_to_logger_php#/log.php?'+Math.random(0, 1000) + '=' + Math.random(0, 1000);
if(supportsCrossOriginResourceSharing) {
xhrTrack(trackUrl);
} else {
imgTrack(trackUrl);
}
}
function xhrTrack(trackUrl) {
var xhr = new XMLHttpRequest();
xhr.open("GET", trackUrl, false);
xhr.onreadystatechange = function() {
if(xhr.readyState >= this.OPENED) xhr.abort();
}
try { xhr.send() } catch(e) {}
}
function imgTrack(trackUrl) {
var trackImg = new Image(1,1);
trackImg.src = trackUrl;
}