Reputation: 326
Before I begin I'd like to tell all of you that I made a lot of searching for solution of this problem on my own.
Here is my nodejs server:
var http = require('http');
http.createServer(function (req, res) {
console.log("Recived request url " + req.url);
var sname = req.url.search("name");
if(sname != -1){
sname = sname + "name".length + 1;
var from = sname;
while(req.url[sname] != '?' && sname<req.url.length){
sname++;
}
var name = req.url.substring(from,sname);
console.log("Returning parameter of name - " + name);
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(name+'\n');
}
else{
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Error - ask about name\n');
}
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
It listens on port 1337 and if request url is correct it returns some string.
Here is my javascript code asking nodejs for answer.
function httpGet(theUrl){
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", theUrl, true );
xmlHttp.send( null );
return xmlHttp.responseText;
}
var url = httpGet("http://127.0.0.1:1337/?name=Mateusz");
setTimeout(function(){
document.getElementById("actualnewsspace").innerHTML=url;
var xurl = httpGet("http://127.0.0.1:1337/?"+url);
},5000)
returned xmlHttp.responseText is blank. Why? That's my question.
That's what my nodejs server has to say in this matter
Recived request url /?name=Mateusz
Returning parameter of name - Mateusz
Recived request url /?
If I curl my server it returns mi proper value.
Upvotes: 4
Views: 1308
Reputation: 943579
xmlHttp.responseText
hasn't been populated when you return it. Ajax is Asynchronous.
See Using XMLHttpRequest and bind an event handler to listen for when the HTTP response has arrived and process the data in that.
Upvotes: 3