0

i am trying to get html from a web page though xmlhttprequest using node.js. The code that i have found on internet is:

var sys = require ('sys'),
url = require('url'),
XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest,
http = require('http'),
qs = require('querystring');
http.createServer(function (req, res) {
    var temp        
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
        var loc = xhr.responseText.search("Right Now");
        temp = xhr.responseText.substr(loc,loc+10);
        //console.log(temp);
        }
    }
xhr.open('GET', 'http://www.weather.com/weather/today/37.229572,-80.413940', true);
xhr.send(null);
console.log(temp);
res.write("pappu\n");
res.end();
}
).listen(80);

I want to use xhr.responseText outside the function but i am unable to do it. I have tried not using var with temp to make it global but node.js is giving error on this.

Please help me Regards

Ali Haider
  • 33
  • 4

2 Answers2

0

Are you dead set on using xmlhttprequest? Since you are using node, there are easier and cleaner solutions that will wrap this functionality for you, like the popular request library. Here's an example that will achieve the results you want in many fewer lines of code:

var request = require('request');
request.get('http://www.weather.com/weather/today/37.229572,-80.413940', callback);

function callback(err, res){
  if (err) return console.error(err);
  console.log(res.body);
}

All you have to do is run npm install request to get this to run correctly. If for some reason you need to use xmlhttprequest let me know and I'll update this answer with instructions, just figured I'd suggest an easier way to achieve the same thing first : )

Jeff Escalante
  • 3,137
  • 1
  • 21
  • 30
  • thank you jeff. this is OK with me but the problem is still the same, how do i write it in response inside the function or get its value outside the function ..???? and yes .. i am dead set on using node.js and javascript – Ali Haider Oct 26 '13 at 21:47
  • He didn't suggest not using Node or JavaScript. – Quentin Oct 26 '13 at 22:30
  • Updated the answer to the easiest way to move the response into a new scope. Since the ajax function is asynchronous, you must handle the response within some function. this is about as clean as you can get it. I wrote a lengthy explanation of functions and asynchrony on [this answer](http://stackoverflow.com/questions/18886089/how-do-i-callback-with-js-function/18886376#18886376) which might help you to understand how these things work better : ) – Jeff Escalante Oct 27 '13 at 01:08
0

xmlhttprequest works asynchronously, so your console.log(temp); will not work as you expect. Because temp variable will not be defined until the response is received. Hence, any attempt to print it immediately after xhr.send(null); will likely give an error.

hswner
  • 582
  • 1
  • 4
  • 17