XMLHttpRequest strange on IE11, ok on Edge and Chrome - javascript

i try to do the following
but it doesn't work on IE11 in my case?
var request = new XMLHttpRequest();
function doStuff()
{
console.log("next request");
doRequest();
}
function doRequest() {
request.open("GET","http://127.0.0.1/poll.php", true);
request.onloadend = doStuff;
request.send();
}
doRequest();
The PHP script poll.php is sleeping for one second.
Now the Point: The Egde and Chrome are requesting round about once per second
but the IE doesen't, it spams the log with 1000 requests per second AND they dont even got execute.
If i remove the endless Loop, the IE is doing one request,
if it is a endless Loop, the IE is doing nothing except spamming the log.
Hope u can unterstand me and give me a hint,
how to solve my Problem.
Best Regards.

It seems IE caches the request, therefore the 2nd and subsequent requests finish immediately - after running the code once, even the first request would do so
As a side note, I'm actually surprised other browsers don't cache XHR requests - at least, they don't seem to if the question is an accurate reflection of browser behaviour!
One solution is to add a random "search" (or query) string to the URL
function doRequest() {
request.open("GET","http://127.0.0.1/poll.php?_"+Math.random(), true);
// ^^^^^^^^^^^^^^^^^
request.onloadend = doStuff;
request.send();
}
Another would be to have the server respond with response headers that tell the browser "don't cache this" - in the case of PHP (because the request clearly is made to PHP)
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
(shamelessly "borrowed" from https://stackoverflow.com/a/13640164/5053002 - so if it's wrong don't blame me, I haven't used PHP in a few years)

Related

Ajax Call empty response on Google chrome Mobile

i searched for an answer that fix my problem a lot, but none of the topic fit my scenario..
I have to make an AJAX call inside my application, it work fine on ALL desktop browser, and on SOME mobile browser (for example on my ASUS zenPhone native browser it work correctly, even on my iPhone from work (FF and Safari)) but no way in google Chrome (mobile), in this one the call complete but the response it's empty (only empty, no error provided)... i ask some friend to test it too and similar result occours (empty response) .... i have an https server and an https endpoint
there is my code:
<script>
var x = Math.floor((Math.random() * 10000000) + 2000);
var data = JSON.stringify({
"Token": x,
"Subject": "testAPI"
});
var xhr = new XMLHttpRequest();
xhr.addEventListener("readystatechange", function () {
if (this.readyState === 4) {
//console.log(this.responseText);
var dataJ = JSON.parse(this.responseText);
var dataA = dataJ.Questions;
alert(dataA[0].img);//this is already empty on my mobile :(
dataA.forEach(function(entry) {
//console.log(entry);
});
}
});
xhr.open("POST", url);
xhr.setRequestHeader("content-type", "application/json");
xhr.setRequestHeader("cache-control", "no-cache");
xhr.send(data);
</script>
Server side CORS are enabled, and as i said it works flawless on all desktop i tested on ... i don't know if i can provide the url to you guys(i have to ask # the API provider) but if you give me some hints it would be nice ...
thanks a lot for your time!
[EDIT]
after some trouble i get an error(Testing remotly from my phone to my PC with dev tools)
Failed to load resource: net::ERR_INSECURE_RESPONSE
on the other device i didn't get this error...
This is a long shot but, try to set the content type header to :
xhr.setRequestHeader("content-type", "text/plain");
This should suppress the CORS preflighting done by chrome which causing the empty response.

js php, ajax remembers previously loaded content

I have the weird issue, I have been looking for the solution for a while with no result. I'm developing a website, decided to load every subpage(content) dynamically via AJAX(also .js and .css files for each subpage). Now, when I'm working on it and change scripts/css for some file and refresh the page, it doesn't load them. It's like AJAX remembers the previous version, because when I turn it all of and come back after few hours it changes (!). Any ideas for this one? I want to avoid remembering anything by site memory(or anything) so I could work on this normally. I don't use jquery, I use pure js and my own function for ajax connection, maybe I should add there something? Here it is:
function sendQuery( data )
{
var http = new XMLHttpRequest();
var url = data["url"];
var params = "";
var query = data["params"];
for(var key in query)
params+=key+"="+query[key]+"&";
params=params.substring(0,params.length-1);
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.send(params);
http.onreadystatechange = function()
{
if(http.readyState == 4 && http.status == 200)
{
data["result"](http.responseText);
}
}
}
Not sure entirely what you mean, but this sounds like a caching issue, why not append the current time or a similar random string to the request as a separate parameter? This level of uniqueness should prevent the request response from being cached by the browser.
e.g. '?nocache='+new Date().getTime()
You may also want to prevent the server side response from caching the content returned by the call by setting the appropriate headers (e.g.):
response.setHeader( "Pragma", "no-cache" );
response.setHeader( "Cache-Control", "no-cache" );
response.setDateHeader( "Expires", 0 );
It seems highly related with your caching policy.
If you're hosting site with apache,
Check .htaccess in your root directory you might see something like this:
# Set up 2 Hour caching on commonly updated files
<FilesMatch "\.(xml|txt|html|js|css)$">
ExpiresDefault A7200
Header append Cache-Control "proxy-revalidate"
</FilesMatch>
The setting above set expire time to 7200 seconds = 2 hours.
To disable cache under development:
# Force no caching for dynamic files
<FilesMatch "\.(xml|txt|html|js|css)$">
ExpiresActive Off
Header set Cache-Control "private, no-cache, no-store, proxy-revalidate, no-transform"
Header set Pragma "no-cache"
</FilesMatch>
Then it should works properly.
Another way is to change this line:
var url = data["url"];
To:
var url = data["url"]+"&ts="+(new Date().valueOf());
To avoid the cache. Note: it's just pseudo code. "?" Should be handled if there hasn't one.
Hope it helps :)

Prevent browser from caching AJAX requests

I've setup an app and it works fantastic on Opera and Firefox, but on Google Chrome it caches the AJAX request and will give stale data!
http://gapps.qk.com.au is the app. When ran in Chrome it doesn't even send the AJAX requests, but when tried in another browser it always does the AJAX request and returns data.
Is there any method (Apache/PHP/HTML/JS) to stop Chrome from doing this behavior?
The AJAX call:
function sendAjax(action,domain,idelement) {
//Create the variables
var xmlhttp,
tmp,
params = "action=" + action
+ "&domain=" + encodeURIComponent(domain)
xmlhttp = new XMLHttpRequest();
//Check to see if AJAX request has been sent
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
$('#'+idelement).html(xmlhttp.responseText);
}
};
xmlhttp.open("GET", "ajax.php?"+params, true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//console.log(params);
xmlhttp.send(params);
}
sendAjax('gapps','example.com','gapps');
The browser cache behaves differently on different settings. You should not depend on user settings or the user's browser. It's possible to make the browser ignore headers also.
There are two ways to prevent caching.
--> Change AJAX request to POST. Browsers don't cache POST requests.
--> Better Way & good way: add an additional parameter to your request with either the current time stamp or any other unique number.
params = "action=" + action
+ "&domain=" + encodeURIComponent(domain)
+ "&preventCache="+new Date();
Another alternative to the Javascript solution is to use custom headers:
In PHP it would look like this:
<?php
header("Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0");//Dont cache
header("Pragma: no-cache");//Dont cache
header("Expires: Thu, 19 Nov 1981 08:52:00 GMT");//Make sure it expired in the past (this can be overkill)
?>
I was using jQuery ajax request when I ran into this problem.
According to jQuery API adding "cache: false" adds a timestamp like explained in the accepted answer:
This only works with GET and HEAD requests though but if you're using POST the browser doesn't cache your ajax request anyways. There's a but for IE8, check it out in the link if needed.
$.ajax({
type: "GET",
cache: false,
});
Below line of code worked for me.
$.ajaxSetup({ cache: false });

XMLHttpRequest receiving no data or just "undefined"

i try to make a Firefox Addon which runs a XMLHttp Request in Javascript. I want to get the data from this request and send it to *.body.innerhtml.
That's my code so far...
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
setTimeout(function() { set_body(xhr.responseHtml); }, 6000);
Instead of receiving the data, I get "undefined". If I change xhr.responseHtml to responseText I get nothing. I don't know why I'm getting nothing. I'm working on Ubuntu 12.04 LTS with Firefox 12.0.
If you need any more details on the script please ask!
Update:
set_body Function
document.body.innerHTML = '';
document.body.innerHTML = body;
document.close();
Update SOLVED:
I had to determine the RequestHeaders (right after xhr.open):
xhr.setRequestHeader("Host", "xxx");
For following Items: Host, Origin and Referer. So it seems there was really a problem with the same origin policy.
But now it works! Thanks to all!
when you set the last param of open to true you are asking for an async event. So you need to add a callback to xhr like so:
xhr.onReadyStateChange = function(){
// define what you want to happen when server returns
}
that is invoked when the server responds. To test this without async set the third param to false. Then send() will block and wait there until the response comes back. Setting an arbitrary timeout of 6 seconds is not the right way to handle this.
This code should work:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState == 4) {
set_body(xhr.responseText);
}
};
xhr.open("GET", "http://xx.xxxxx.com", true);
xhr.send();
Make sure that you are getting a correct response from URL http://xx.xxxxx.com. You may have a problem with cross-domain calls. If you have a page at domain http://first.com and you try to do XMLHttpRequest from domain http://second.com, Firefox will fail silently (there will be no error message, no response, nothing). This is a security measure to prevent XSS (Cross-site scripting).
Anyway, if you do XMLHttpRequest from a chrome:// protocol, it is considered secure and it will work. So make sure you use this code and make the requests from your addon, not from your localhost or something like that.

How to prevent Ajax/javascript result caching in browsers?

How to prevent browsers from caching Ajax results? I have and event triggered Ajax script the displays results only when the browsers data has been cleared.
Tested in IE6 and Firefox 3.0.10
The random URL works, but it's kind of a hack. HTTP has solutions built in that should work. Try using the solution indicated here. Basically, set the headers:
"Pragma": "no-cache",
"Cache-Control": "no-store, no-cache, must-revalidate, post-check=0, pre-check=0",
"Expires": 0,
"Last-Modified": new Date(0), // January 1, 1970
"If-Modified-Since": new Date(0)
Add a random query string to the URL you are sending.
E.g. if the Ajax request is sent to "http://www.xyz.com/a"
then add a random string at the end: "http://www.xyz.com/a?q=39058459ieutm39"
I've used the jQuery {cache: false} method and it worked like a charm.
The complete code example is like this:
$.ajaxSetup({cache: false});
There are two techniques for this that I'm aware of.
Add some sort of query string to the AJAX request URL so that it's always unique. A millisecond timestamp (perhaps combined with a random value) is good for this
Set HTTP cache control headers on the AJAX response so that the browser doesn't cache it
using jQuery you can set global ajax setting: { cache: false }. See it in jquery ajax docs

Categories

Resources