I have the following code.
var d3_ad = 1;
function displayD3Ad(){
var query_string = '?d3_ad='+d3_ad;
query_string += '&location='+escape(location);
//document.write('<iframe src="index.php'+query_string+'"></iframe>');
var data = httpRequest('http://localhost/test/index.php','GET',query_string);
document.write(data);
}
function httpRequest(strURL,type,query) {
var request = false;
if (window.XMLHttpRequest) {// Mozilla/Safari
request = new XMLHttpRequest();
} else if (window.ActiveXObject) { //Internet Explorer
request= new ActiveXObject("Microsoft.XMLHTTP");
}
request.open(type, strURL + query, true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.onreadystatechange = function() {
if (request.readyState == 4) {
return request.responseText;
}
}
request.send(null);
}
displayD3Ad();
now when it writes out the data it is saying undefined. It seems like it isnt returning the data. I looked in firebug and it completes and shows the response that shoudl be there. Any help is appreciated. I just need to set the data variable so that I can use it later on.
You’re right, in JavaScript you’d have to handle the response value in a callback. Which is not ideal for serious application.
There is an extension to the JavaScript language called StratifiedJS. It runs in every browser, and it allows you to get the response value directly (instead of undefined)
You can enable Stratified JavaScript e.g. by including Oni Apollo ( http://onilabs.com/docs ) in your webpage like:
And the your code would look like this:
This is using the Apollo toolkit so you don’t have to write your own HttpRequest function, it’s already there in the “http” module.