IE11 XMLRequest Access is Denied - javascript

I tried to do a simple AJAX request on http://localhost:8080/ and I get an error right away when using IE 11. I don't think IE is even trying to send anything.
Did somebody meet this issue?
Here is a fiddle showing this behavior,
html:
<button id='btn1'>launch</button>
onLoad:
var xhr,btn=document.getElementById('btn1');
btn.onclick=onButton;
var onReadyState=function(){
console.log('ready state:'+_xhr.readyState);
if(xhr.readyState===4){
console.log('status:'+_xhr.status);
}
}
function onButton(){
xhr=new window.XMLHttpRequest();
xhr.onreadystatechange=onReadyState;
xhr.open('POST','http://localhost:8080/ScanAPI/v1/client');
xhr.send();
}
You will need to launch the IE F12 developer tool, before trying and you will see IE catching the exception.
Any help on this would be greatly appreciated.
Thanks!

It doesn't work because you are referencing an object named _xhr that does not exist within the scope of the onReadyState function.
You should be using this instead :
var onReadyState = function() {
if (this.readyState === 4) {
console.log('status :' + this.status);
}
};
That's because the XMLHttpRequest object will call back onReadyState with its own context, which is accessible through this in your function.
Also note that the onReadyState function misses a semi-colon at the end of its definition, didn't notice it at first sight.
EDIT : I also noticed that IE10 (and IE11) does interpret some HTTP response code as network errors (such as with a 401 response code), if it is your case, then it makes sense that IE fails at retrieving your resource.
I forked your fiddle and wrote a simple page that works well with IE11.

Related

Meteor method not working properly in mozilla

I am trying to make a call to a meteor method, to insert a document before redirecting the user to the relevant url (using the generated document _id).
The code currently works on chromium but not on firefox, where on firefox it appears to just get redirected right away without actually inserting anything.
I've attached my code at the bottom. Can anyone tell me what went wrong and what can I do to fix it? Why will chrome and firefox behave differently in this situation?
Any help provided is greatly appreciated!
client.js
newDoc(){
Meteor.call('addDoc',{
// some parameters
})
}
clientandserver.js (Meteor method)
'addDoc'(obj){
console.log(obj); // does not output anything on firefox
DocumentData.insert({
//some parameters
},function(err,documentID){
if (Meteor.isClient){
window.location = '/docs/' + documentID;
// redirection happens before insertion on firefox
}
});
}
Bring window.location to the client side. Like:
newDoc(){
Meteor.call('addDoc', data, function(error, result){
if(result){
window.location = '/docs/' + documentID;
}
})
}
And put only the insertion in server side, like:
'addDoc'(obj){
return DocumentData.insert({
//some parameters
});
}
I've used this structure and it works for me in both Firefox & Chrome.

online offline check using javascript [duplicate]

This question already has answers here:
Detect the Internet connection is offline?
(22 answers)
Closed 8 years ago.
How do you check if there is an internet connection using jQuery? That way I could have some conditionals saying "use the google cached version of JQuery during production, use either that or a local version during development, depending on the internet connection".
The best option for your specific case might be:
Right before your close </body> tag:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.10.2.min.js"><\/script>')</script>
This is probably the easiest way given that your issue is centered around jQuery.
If you wanted a more robust solution you could try:
var online = navigator.onLine;
Read more about the W3C's spec on offline web apps, however be aware that this will work best in modern web browsers, doing so with older web browsers may not work as expected, or at all.
Alternatively, an XHR request to your own server isn't that bad of a method for testing your connectivity. Considering one of the other answers state that there are too many points of failure for an XHR, if your XHR is flawed when establishing it's connection then it'll also be flawed during routine use anyhow. If your site is unreachable for any reason, then your other services running on the same servers will likely be unreachable also. That decision is up to you.
I wouldn't recommend making an XHR request to someone else's service, even google.com for that matter. Make the request to your server, or not at all.
What does it mean to be "online"?
There seems to be some confusion around what being "online" means. Consider that the internet is a bunch of networks, however sometimes you're on a VPN, without access to the internet "at-large" or the world wide web. Often companies have their own networks which have limited connectivity to other external networks, therefore you could be considered "online". Being online only entails that you are connected to a network, not the availability nor reachability of the services you are trying to connect to.
To determine if a host is reachable from your network, you could do this:
function hostReachable() {
// Handle IE and more capable browsers
var xhr = new ( window.ActiveXObject || XMLHttpRequest )( "Microsoft.XMLHTTP" );
// Open new request as a HEAD to the root hostname with a random param to bust the cache
xhr.open( "HEAD", "//" + window.location.hostname + "/?rand=" + Math.floor((1 + Math.random()) * 0x10000), false );
// Issue request and handle response
try {
xhr.send();
return ( xhr.status >= 200 && (xhr.status < 300 || xhr.status === 304) );
} catch (error) {
return false;
}
}
You can also find the Gist for that here: https://gist.github.com/jpsilvashy/5725579
Details on local implementation
Some people have commented, "I'm always being returned false". That's because you're probably testing it out on your local server. Whatever server you're making the request to, you'll need to be able to respond to the HEAD request, that of course can be changed to a GET if you want.
Ok, maybe a bit late in the game but what about checking with an online image?
I mean, the OP needs to know if he needs to grab the Google CMD or the local JQ copy, but that doesn't mean the browser can't read Javascript no matter what, right?
<script>
function doConnectFunction() {
// Grab the GOOGLE CMD
}
function doNotConnectFunction() {
// Grab the LOCAL JQ
}
var i = new Image();
i.onload = doConnectFunction;
i.onerror = doNotConnectFunction;
// CHANGE IMAGE URL TO ANY IMAGE YOU KNOW IS LIVE
i.src = 'http://gfx2.hotmail.com/mail/uxp/w4/m4/pr014/h/s7.png?d=' + escape(Date());
// escape(Date()) is necessary to override possibility of image coming from cache
</script>
Just my 2 cents
5 years later-version:
Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.
On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.
You can mimic the Ping command.
Use Ajax to request a timestamp to your own server, define a timer using setTimeout to 5 seconds, if theres no response it try again.
If there's no response in 4 attempts, you can suppose that internet is down.
So you can check using this routine in regular intervals like 1 or 3 minutes.
That seems a good and clean solution for me.
You can try by sending XHR Requests a few times, and then if you get errors it means there's a problem with the internet connection.
I wrote a jQuery plugin for doing this. By default it checks the current URL (because that's already loaded once from the Web) or you can specify a URL to use as an argument. Always doing a request to Google isn't the best idea because it's blocked in different countries at different times. Also you might be at the mercy of what the connection across a particular ocean/weather front/political climate might be like that day.
http://tomriley.net/blog/archives/111
i have a solution who work here to check if internet connection exist :
$.ajax({
url: "http://www.google.com",
context: document.body,
error: function(jqXHR, exception) {
alert('Offline')
},
success: function() {
alert('Online')
}
})
Sending XHR requests is bad because it could fail if that particular server is down. Instead, use googles API library to load their cached version(s) of jQuery.
You can use googles API to perform a callback after loading jQuery, and this will check if jQuery was loaded successfully. Something like the code below should work:
<script type="text/javascript">
google.load("jquery");
// Call this function when the page has been loaded
function test_connection() {
if($){
//jQuery WAS loaded.
} else {
//jQuery failed to load. Grab the local copy.
}
}
google.setOnLoadCallback(test_connection);
</script>
The google API documentation can be found here.
A much simpler solution:
<script language="javascript" src="http://maps.google.com/maps/api/js?v=3.2&sensor=false"></script>
and later in the code:
var online;
// check whether this function works (online only)
try {
var x = google.maps.MapTypeId.TERRAIN;
online = true;
} catch (e) {
online = false;
}
console.log(online);
When not online the google script will not be loaded thus resulting in an error where an exception will be thrown.

NS_ERROR_FAILURE with JS XMLHttpRequest

I'm trying to load the source of a web page, as shown in "Javascript:The Definitive Guide" p.481, using firefox.
Here's my code:
var request = new XMLHttpRequest();
request.open("GET", "http://finance.yahoo.com/q?s=PG", false);
request.send(null);
if (request.status==200) { alert(request.responseText); }
else {alert("Error "+request.status + ": "+request.statusText);}
</script>
Firebug shows the GET statement, followed by 200 OK X 338ms.
Which looks like it was successful (code 200).
But the next Firebug line says: NS_ERROR_FAILURE, request.send(null);, with no further explanation.
and neither alert gets executed.
It doesn't help if I use help mode, and doesn't run in Chrome either. I don't have a popup or cookie or ad blocker running.
The page loads fine in perl with an LWP get().
If this is an inevitable cross-domain taboo, why doesn't the "definitive guide" say so?
I understand that JSONP returns JSON. I don't want that - I want just a string with the raw source, like with the perl LWP get().
Is this impossible with Javascript?
I suppose I could write a batch file which uses perl to get the source and put it into a JSON file whose name is hard-coded into the JS. But I'd like to avoid that sort of kludge.
In case it helps,
I have run into this problem a couple times before, and ran into it again. If the answer to this question doesn't help you, try adding the following lines which helped me:
request.overrideMimeType('text/xml; charset=UTF-8'); // needed to get utf8 req's to work
or this debug line (which you can monitor on the web console of your browser)
request.onreadystatechange = function() {console.log("statechanged. url= " + url);};
before your
request.open()
where url is a var that holds the url you are trying to request. Sometimes it will give you that cryptic error if there is a problem getting the url, in my (last) case, it was because the url was malformed. Hope that helps someone out there.

XDomainRequest - not calling...not doing anything

I've a problem...I use jQuery ajax to call a web service that returns XML. The jQuery ajax stuff works awesome for every browser except for ie.
So for ie browsers, I am using XDomainRequest. Here is the code:
if ($.browser.msie && window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", theUserUrl);
xdr.timeout = 95000;
xdr.onerror = function () {
console.log('we have an error!');
}
xdr.onprogress = function () {
console.log('this sucks!');
};
xdr.ontimeout = function () {
console.log('it timed out!');
};
xdr.onopen = function () {
console.log('we open the xdomainrequest');
};
xdr.onload = function () {
// XDomainRequest doesn't provide responseXml, so if you need it:
var xml2 = new ActiveXObject("Microsoft.XMLDOM");
xml2.async = false;
xml2.loadXML(xdr.responseText);
console.log('do we get any response text at all?: ' + xdr.responseText);
ParseOwnershipObjects(xml2);
//AddServiceRequestsToMap(xml2, map, spinner);
};
xdr.send();
}
This exact code works fine elsewhere in the application with a
different url.
The url is fine, it returns exactly what it should in the browser
(and hence why the jquery ajax call works). Couple of things to
note:
I am integrating my own html/javascript with another guy's asp.net
project.
In the global.asax.cs file, I have:
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET,OPTIONS");
}
so I don't think that it's a header problem.
None of my handlers fire. Not the onprogress, ontimeout, onerror...nothing!
I don't have time to convert the web service to JSON.
Any thoughts?
Thanks!
Disclaimer - I actually haven't used 'XDomainRequest' - when using jQ I set data to jsonp for xdomain requests...
When debugging - are you using IE Dev tools (F12)? If not, the error is likely console.log
EDIT:
mea culpa, disregard the jsonp stuff - missed the part you mentioned XML
Update:
Out of curiosity I'm trying XDomainRequest. I copied your code and just added a value for theUserUrl.
as above/expected, unless I have Internet Explorer Developer tools running, console is undefined - and may give the impression that "none of your handlers are firing".
Once I have the IE dev tools enabled (docked or otherwise) xdr.onerror fires. we have an error is logged in the IE console. So while there is an error, the handler does fire.
A quick read on XDomainRequest requires the responding server to have the Access-Control-Allow-Origin header. I'm calling my own server and I know I don't have this header set, so without further debugging, it would be a good guess that's why xdr.onerror is being fired.
As it turns out, there were special characters in the url parameters that were not being correctly dealt with by the XDomainRequest object. Instead of the GET request, I am going to use the POST request on internet explorer-only queries.
EDIT - I ended up switching the web service over to return output in JSON format, thus negating the need for the XDomainRequest. Using JSON speeds things up a bit too, I recommend it!

Why does this JavaScript work on Safari, but not Firefox?

I have HTML file. I tried the code on Safari and it was working fine. But when I tried this on Firefox, it’s not working.Can anyone suggest how to make it working on firefox?
On click on undo button I want to retrieve contents from the jsp file. Thats working when I used this code on safari on my mac.. but when I open the same file using firefox its not working. I am not sure is it due to browser settings or due to some other reason. I checked browser setting of firefox 3.6.12 installed on mac also it is enabled for javascript and java...
When I checked on HTTPfox it showed in Error loading content (NS_ERROR_DOCUMENT_NOT_CACHED) in the contents
Can anyone suggest whats going wrong???
XMLHttpRequests only work when the request is on the same domain as the JavaScript making the request. So, your call to xmlHttp.open() would only work if that HTML file was hosted on csce.unl.edu.
Can the ubuntu box access the url http://csce.unl.edu:8080 ? It may be network/proxy/firewall settings on the virtual machine or in Firefox settings.
I'd try running firefox on the Mac and see where that takes me. If that doesn't work Then the problem is the browser, if it does, it's the way you are loading the site
Use JQuery. It has an AJAX library which does these browser compatibility checks for you.
Also, Firebug may come in handy, to see whether the request is being sent and see what the response is.
I opened firebug > console and pasted
var xmlHttp, handleRequestStateChange;
handleRequestStateChange = function() {if (xmlHttp.readyState==4 && xmlHttp.status==200) { var substring=xmlHttp.responseText; alert(substring); } }
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://csce.unl.edu:8080/test/index.jsp?id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange; xmlHttp.send(null);
And i saw everything working. What the error exactly? Can you open firebug and look at javascript errors.
Edit try this:
var req = new XMLHttpRequest();
req.open('GET', '/');
req.onreadystatechange = function (aEvt) {
if (req.readyState == 4) {
if(req.status == 200)
alert(req.responseText);
else
alert("Error loading page\n");
}
};
req.send(null);

Categories

Resources