INVALID_STATE_ERR: DOM Exception 11 - javascript

Ok, I've created a working javascript ajax file, but it generates an absurd number of these dom exceptions. I'm not sure why that is, because from what I can see, all the elements I call are currently still in existance.
The code is here:
window.onload = function(){init();}
function init() {
ajax = ajaxInit();
setInterval(function(){ajaxContact(ajax);},2000);
ajaxContact(ajax);
ajax.onreadystatechange = function() {update(ajax);}
}
function ajaxInit() {
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (ajax) {
document.getElementById("status").innerHTML = "AJAX initialized";
return ajax;
}
else {
docuement.getElementById("status").innerHTML = "Error: AJAX not available";
return false;
}
}
function ajaxContact(ajax) {
try {
ajax.open("GET","updateAjax.php?" + "ran=" + Math.random(),true);
ajax.send();
}
catch (err) {
alert(err.message);
document.getElementById("status").innerHTML = "Error contacting server";
document.getElementById("loading").src = "images/redx.png";
}
}
function update(ajax) {
if (ajax.readyState==4 && ajax.status==200){
dataObj = eval('(' + ajax.responseText + ')');
document.getElementById("status").innerHTML = dataObj.status;
document.getElementById("frameNumber").innerHTML =
"Frame:" + dataObj.firstFrame + "/" + dataObj.lastFrame;
document.getElementById("thumbnail").src = dataObj.imgSrc;
}
if (ajax.status==404) {
document.getElementById("status").innerHTML = "Ajax updater not found";
document.getElementById("loading").src = "images/redx.png";
}
}

You are probably trying to call open and send on ajax, but it throws errors if the request has not finished within the two seconds between each call by setInterval. You need to check in each call whether the ajax object has been sent already or is ready for opening (check ajax.readyState).
In Chrome, the line
if (ajax.status==404) {
causes the error by accessing the status before ajax.readyState is HEADERS_RECEIVED (2), LOADING (3), DONE (4). Try making it
if (ajax.readyState == 4 && ajax.status==404) {
to make sure that the object is ready before accessing the status.

Related

Firefox extension: use promise in browser.webRequest.onBeforeRequest.addListener

I'm working on a firefox extension and using browser.webRequest.onBeforeRequest.addListener.
I need to redirect or release the webRequest until I have information back from calls made within the handler.
I used to use synchronous ajax, but the page was blocked for too long when the network was poor. If the request time exceeds 5 seconds, I want to cancel the ajax request. But it seems impossible to set a timeout on a synchronous call.
These days I try to use asynchronous ajax and use the methods(return new Promise) provided in https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/onBeforeRequest. I tried several days but failed.
My codes:
var LOOKUP_URL = "https://a.b.c.com/";
var urlLookup = new UrlLookup(LOOKUP_URL);
var blockList = [];
browser.webRequest.onBeforeRequest.addListener(redirectAsync, {urls: ['<all_urls>']},, ["blocking"]);
function redirectAsync(details) {
var url = details.url;
return new Promise(function(resolve,reject){
var urlLookupResult = urlLookup.check(url, LookupComplete);
if(urlLookupResult.result){
var redirectUrl = urlLookupResult.url;
resolve({redirectUrl})
}
})
}
function LookupComplete(url, data, error){
if(data.result){
blockList.push(url);
localStorage.setItem("blockList",JSON.stringify(blockList));
return {
result: true,
url: "https://aaa.bbb.com/alerts.php?url=" + url;
}
}else {
return null
}
}
codes in urlLookup.js:
function UrlLookup(domain) {
function check(url, callback) {
var data;
var http_request = new XMLHttpRequest();
var timeId = window.setTimeout(function(){
http_request.abort();
},5000)
http_request.open("GET", domain + 'url='+url);
try {
http_request.send();
http_request.onreadystatechange = function(){
if(http_request.readyState == 4 && http_request.status == 200){
window.clearTimeout(timeId);
data = JSON.parse(http_request.response);
return callback(url, data);
}
}
} catch (e){
return callback(url, null, "Error");
}
};
return {
check: check
};
}
How should I modify it?

Why isn't JavaScript throwing exceptions as the result of an asynchronous HTTP (AJAX) request?

I've written the following JavaScript function which is very simple, it takes an ID and which then is sent to a PHP page, which echoes out some JSON. It passes the ID into the PHP page via GET.
For example, if I was to make the following GET request: /processing/getAccountInfo.php?id=5, it would return this (got from a database): {"username":"carefulnow","profileImg":null}. This is correct, so I know my PHP is working fine.
My JavaScript code that originally called the AJAX now needs to process it, echo it out and check it for errors. If the PHP function encounters any errors, the returned JSON will contain an "errorMsg" which contains the name of the PHP exception that it encountered including a specific message (Exception::getMessage()). An example error result would be {"errorMsg":"PDOException: some error..."}.
function getAccountInfo(id) {
var loading = document.getElementById("loading");
var inner = document.getElementById("accInfInner");
var name = document.getElementById("accInfName");
var img = document.getElementById("accInfImg");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
try {
var response = JSON.parse(this.responseText);
if (response.errorMsg === undefined) {
if (response.username === undefined || response.profileImg === undefined) {
throw new Error("Could not get the username and profile image. Try logging in then back out.");
}
name.innerHTML = response.username;
// The profile image is not required.
if (response.profileImg !== null) {
img.src = response.profileImg;
} else {
img.src = "/assets/img/defaultuser.jpg";
}
loading.style.display = "none";
inner.style.display = "block";
} else {
throw new Error(response.errorMsg);
}
} catch (exception) {
inner.innerHTML = "Error. Hover for details.";
inner.title = exception.message;
}
}
};
xmlhttp.open("GET", "/processing/getAccountInfo.php?id=" + id, true);
xmlhttp.send();
}
The problem, however, is that the throw statements aren't working. If an error is thrown from the PHP, nothing happens (no errors in the console)! My IDE (PHPStorm 2017.1) gives the following error: "'throw' of exception caught locally", which after a lot of searching, I cannot find anyone else having this same issue. Is it something to do with the GET request been asynchronous, or is it something a lot simpler I'm not seeing?

How to catch a lost connection in AJAX call

I have the below code:
sendRequest : function(data){
var me = this;
this._createData(data);
try{
this.req.open(this.method,this.page,true);
this.req.onreadystatechange=function()
{
if (this.readyState==4 && this.status==200)
{
if(this.responseText)
var response = eval('(' + this.responseText + ')');
else
response = null;
me.callBack(response);
return false;
}
}
this.req.send(this.data);
} catch(err){
me.callBack(response);
}
},
It works fine, and returns what I expect it to return, but when the connection is lost, it doesn't go into the catch block. What I want to know is how catch the request when server page is not available.
Here's an example from Microsoft's doc page for onreadystatechange:
function reportStatus()
{
if (oReq.readyState == 4 /* complete */) {
if (oReq.status == 200 || oReq.status == 304) {
alert('Transfer complete.');
}
else {
// error occurred
}
}
}
var oReq = new XMLHttpRequest();
oReq.open("GET", "http://localhost/test.xml", true);
oReq.onreadystatechange = reportStatus;
oReq.send();
Look where it says // error occurred.
There is a similar code example on this MDN documentation page.
I set a setTimeout before I send the Ajax call:
var timeout = window.setTimeout("functionToCallOnTimeout()", 2000);
inside functionToCallOnTimeout I stop the call:
oReq.current=null;
On a positive answer I clear the timeout:
timeout = null;

basic xmlHttp question

I 'm having some trouble with my javascript code calling my php. Does anyone see an error in the following code? I swear I'm using code just like this on another part of the site...
var xmlHttp = createXmlHttpRequestObject();
var favSongArray = [];
function createXmlHttpRequestObject(){
var xmlHttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e){
var XmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for(var i = 0; i < XmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new ActiveXObject(XmlHttpVersions[i]);
}
catch(e){}
}
}
if(!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp){
alert("sever is available");
//if yes try
try{
xmlHttp.open("GET", "php/getUntimed.php", true);
xmlHttp.onreadystatechange = function(){handleRequestStateChange();};
alert("attempted to call p_handleRequestStateChange_test");
xmlHttp.send(null);
}//end try
catch(e){
alert("Can't connect to server: \n" + e.toString());
}//end catch
}//end if xmlHHttp
}//end function
function handleRequestStateChange(){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
u_handleServerResponse();
}//end try
catch(e){
alert("Error reading the response: " +e.toString());
}//end catch
}//end if
else{
alert("There was a problem retriving the data:\n" + xmlHttp.statusText);
}//end else
}//end if
}//end function
function u_handleServerResponse(){
//need to clear array each time
var response = xmlHttp.responseText;
favSongArray = response.split("+");
alert("made it here");
//getFlashMovie("trackTimer").trackTimer(favSongArray[0]);
}
process() is called from an onSubmit trigger. I keep getting a xmlHttp.status of zero. Does that make sense to anyone? Thanks
status == 0 usually means it was aborted -- either by pressing ESC or by changing the current address.
Or, since you're using a global xmlHttp, you may be calling open and/or send before the last request has had time to finish. Not entirely sure which, but one of them starts by calling abort.
Just navigate here.
http://docs.jquery.com/Ajax
Simple Example:
$.get('MyUrl.aspx', 'MyId=' + id, function(data){
$(data).appendTo($('#MyDiv'));
});
As Jonathan Lonowski says, status == 0 means aborted, and you said you execute that script onsubmit which would trigger the form to submit, thus reload the page and aborting the Ajax request. Take a look here too.
Why don't you try using ajax frameworks? Like jQuery for example.

xmlHTTPrequest won't open ("GET" , url, true); I'm miffed! PHP

I've been trying to get a url to open but I'm miffed as to why this hasn't worked. The code is listed and explained below. Any help will be deeply appreciated.
The object:
function getXMLHTTPRequest() {
var req = false;
try {
/* for Firefox */
req = new XMLHttpRequest();
} catch (err) {
try {
/* for some versions of IE */
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (err) {
try {
/* for some other versions of IE */
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (err) {
req = false;
}
}
}
return req;
}
The object is called like this:
<script type="text/javascript">
var myDelete = new getXMLHTTPRequest();
</script>
Now here's what I want to do:
function removeArticle(id) {
if (myDelete) {
try {
var deletUrl = "delete.php";
var query = deletUrl + "?theid=" + id;
myDelete.open("GET", query, true);
myDelete.onreadystatechange = removeArticleResponse;
myDelete.send(null);
} catch (e) {
alert ("Unable to connect to the server:\n" + e.toString());
}
} else {
alert ("Bad! Very BAD!");
}
}
When I do this:
if (myDelete.open("GET", query, true)) {
myDelete.onreadystatechange = removeArticleResponse;
myDelete.send(null);
} else {
alert ("No road!");
}
The alert("No road!"); shows me that the code doesn't execute passed this point:
if (myDelete.open("GET", query, true)) {
This means that the if (myDelete) { works. The code passes this stage and for some reason stops here: myDelete.open("GET", query, true); It won't open the url. I'm not sure what the problem is.
Edit: Here's the function used to access the server response:
function removeArticleResponse () {
if (myDelete.status == 4) {
if (myDelete.status == 200) {
try {
response = myDelete.responseText;
document.getElementById('displaynewsletterarticleresult').innerHTML = response;
} catch(e) {
alert("An error occured while reading the response:" + e.toString());
}
} else {
alert ("An error occured when attempting to retrieve the data:\n" + myDelete.statusText);
}
}
}
According to this, XMLHttpRequest.open() has no return value, so your check will always fail.
In your response function, do you mean to check .status == 4 instead of .readyState?
All xmlHTTPRequests are bound to the same origin policy. Maybe that's your issue.
You can read more about it at http://en.wikipedia.org/wiki/Same_origin_policy

Categories