My aim is to detect the ad-blocker. I found couple of good examples like FuckAdBlock.
When the ad service call is blocked by the ad-blocked we get the error "err_blocked_by_client".
I want to handle this error, in the following way :
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET","http://static.adzerk.net/ados.js", false);
xhr.onreadystatechange = function (oEvent) {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText)
} else {
console.log("Error", xhr.statusText);
}
}
};
xhr.send();
}
catch(error)
{
console.log("ConsoleLog \n " + JSON.stringify(xhr));
console.log("Error Catched" + error);
}
But in this case i am not able to identify the error reason on catch block.
Please let me know the better option to handle this error or my mistake in this code.
Thanks
You need to have the xhr variable outside of your try. It fails on JSON.stringify(xhr) - because xhr is out of scope. You need to use the onerror error handler to handle the async XMLHttpRequest. You also need to remove the oEvent parameter from the function passed to onreadystatechange. See below:
var xhr = new XMLHttpRequest();
try
{
xhr.open("GET","http://static.adzerk.net/ados.js", true);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log(xhr.responseText)
} else {
console.log("Error", xhr.statusText);
}
}
};
xhr.onerror = function(e) {
console.log("Error Catched" + e.error);
};
xhr.send();
}
catch(error)
{
console.log("ConsoleLog \n " + JSON.stringify(xhr));
console.log("Error Catched" + error);
}
Related
for some reason callback doesn't fire up.
I cut all the extra code out, this is the structure. Perhaps i can't see something wrong here?
(function() {
registerSecendStep = new Page('registerSecendStep', function(name) { //CLIKED THE BUTTON
$('.register-second-step-button').click(function() {
function doAjax(testReferral) {
alert(testReferral); //THIS NEVER GETS PRINTED
}
showHint(function() { doAjax(testReferral); }); //START THE CALL
});
});
function showHint(callback) { //CALLBACK
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert('called'); //THIS GETS ALERTED
callback(true);
}
}
xmlhttp.open("GET", helper.app.HomeSite + "/ajaxresponder?w=" + str, true);
xmlhttp.send();
}
})();
Any help appreciated
testReferral is never defined in the callback. Try:
showHint(function(testReferral) {doAjax(testReferral);});
The following works as expected.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == XMLHttpRequest.DONE) {
if (xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if (xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned:' + xmlhttp.status);
}
}
}
xmlhttp.open("GET", "/services", true);
xmlhttp.send();
It alerts 'something else other than 200 was returned: 404'.
But the following ajax with jquery is not working.
$.ajax({
type: "get",
url: "/services",
error: function() {
console.log("A");
},
complete: function (xhr, data) {
console.log(arguments);
if (xhr.status != 0)
alert('success1');
else
alert('fail2');
}
})
Firebug shows the 404 but alert or console from above code is not called.
I have been relying on jquery to not bother with cross browser issues, and now I am considering falling back to XMLHttpRequest().
It turned out that the issue was due to my build script mangling my code (including jquery). I dont know why it dont work after.
but setting optimize: "none",in the require build grunt file, made everything work.
I am sure there is something that I am missing from this code, I just can not figure out what it is.
Here is the main page:
<script>
function wwCallback(e) {
document.write(e.data);
}
function wwError(e) {
alert(e.data)
}
$(document).ready(function () {
var worker = new Worker("sync.js");
worker.onmessage = wwCallback;
worker.onerror = wwError;
worker.postMessage({
'cmd': 'downloadUser',
'url': 'server.php'
});
console.log("WW Started");
});
</script>
Server.php simply echoes a JSON string and I have verified that it is both valid and working using normal ajax requests.
Here is my web workers code:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
req.send(null);
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);
Could anyone point me in the right direction?
Your problem is in your WebWorker XHR call. You've opened the request, then immediately sent it before you've set up the event handler to handle the response. You just need to move the req.send(null); call below the code that sets up the event handler.
Try this:
function getData(url) {
var req = new XMLHttpRequest();
//expect json
req.open('GET', url);
// req.send(null); // remove this line from here.
req.onreadystatechange = function () {
if (req.readyState == 4) {
if (req.status == 200) {
self.postMessage(req.responseText);
}
}
}
req.send(null); // make the request after your readystatechange
// handler is set up.
}
self.addEventListener('message', function (e) {
var data = e.data;
switch (data.cmd) {
case 'downloadUser':
getData(data.url);
}
self.close();
}, false);
I am adapting the XMLHttpRequest from this tutorial:
var request = new XMLHttpRequest();
request.open('GET', 'http://www.mozilla.org/', true);
request.onreadystatechange = function (aEvt) {
if (request.readyState == 4) {
if (request.status == 200)
console.log(request.responseText)
else
console.log('Error', request.statusText);
}
};
request.send(null);
My code is:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200)
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
else
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
}
}
xhr.send(formData);
But Chrome debugger gives a Uncaught SyntaxError: Unexpected identifier error on the else. What am I doing wrong? Thanks!
You are missing the closing } before and the opening { after the else, as well as the other ones in your if-else - statement.
It works on your tutorial code, because there's only one line in the if-else - statement. When there are multiple lines, you have to block them correctly. (I personally recommend to do this always, even if there's just one line of code. In my opinion it adds to readability and you will not have problems, when you decide to minify your code one day)
Try this:
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://ting-1.appspot.com/submithandlertest", true);
xhr.onreadystatechange = function (aEvt) {
if (xhr.readyState == 4) {
if (xhr.status == 200){
console.log("request 200-OK");
chrome.browserAction.setBadgeText ( { text: "done" } );
}else{
console.log("connection error");
chrome.browserAction.setBadgeText ( { text: "ERR" } );
setTimeout(function () {
chrome.browserAction.setBadgeText( { text: "" } );
}, 2000);
}
}
};
xhr.send(formData);
function processAjaxStateChangeForRowAdd() {
alert(0);
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
processForRowAdd(req.responseText);
} else {
alert("Problem: " + req.statusText);
}
}
}
This code is working fine for IE, Safari and Firefox, but if I remove the alert, then the code will not work in Firefox, though it still works in IE and Safari.
Can anybody give me suggestion why it not working in Firefox without alert?
EDIT: Code that adds a row:
if (window.XMLHttpRequest && browserVersion.indexOf("Microsoft") == -1 ) {
// code for Firefox, Chrome, Opera, Safari
req = new XMLHttpRequest("");
if (req) {
ajaxProcessed = false;
req.onreadystatechange = processAjaxStateChangeForRowAdd;
req.open("POST", url, true);
req.send();
// alert("1");
}
}
The alert is blocking. What this means is that your script is temporarily suspended (even if it's for a few milliseconds). During this time, your AJAX request completes and your req object is being set. You can add a delay (using setTimeout) to your callback to verify this.
I would suggest you post more of your script so that we can help you set up your callback properly. Alternatively, use a library such as jQuery to set up AJAX calls in a cross-browser manner easily.
EDIT: You need to either declare req as a global variable, or use an anonymous function. The following code demonstrates the first method (using a global variable):
var req;
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
if (req) {
req.onreadystatechange = processAjaxStateChangeForRowAdd;
req.open("POST", url, true);
req.send();
}
}
function processAjaxStateChangeForRowAdd() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
processForRowAdd(req.responseText);
} else {
alert("Problem: " + req.statusText);
}
}
}
function getHttp()
{
var xmlhttp;
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
if(typeof XMLHttpRequest != 'undefiend')
{
xmlhttp = new XMLHttpRequest();
}
}
}
return xmlhttp;
}
can you try this:
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText;
} else
alert("status: " + request.status);
}
You should also check for the readyState , the following code might help
req.onreadystatechange=function()
{
if (req.readyState==4 && req.status==200)
{
processForRowAdd(req.responseText)
}
}
Read this for the different values of readyState