Ryan Williams
Ryan Williams

Reputation: 663

how do I use callbacks to wait for httprequest?

When I run the function alertContents, the else is evaluating, I don't want that to happen, how do I i register a callback to wait for the httprequest response ?? bascially the httprequest onreadystatechange needs to use a callback to wait for the response to that the alertcontents function with evaluate the first condition and ultimately alert "hello json" from the body variable set in message.js

<html>
<header><title>This is title</title></header>

<body>
<script type="text/javascript" src="message.js" ></script>

<span id="ajaxButton" style="cursor: pointer; text-decoration: underline">
 Make a request
</span>

<script type="text/javascript">
 (function() {
 var httpRequest;
 document.getElementById("ajaxButton").onclick = function() { makeRequest('message.js'); };
 function makeRequest(url) {

    if (window.XMLHttpRequest) { // Mozilla, Safari, ...
      httpRequest = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // IE
       try {
        httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
       } 
      catch (e) {
        try {
          httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
        } 
      catch (e) {}
      }
    }
    if (!httpRequest) {
      alert('Giving up :( Cannot create an XMLHTTP instance');
      return false;
    }
    httpRequest.onreadystatechange = cbalertContents;
    httpRequest.open('GET', url);
    httpRequest.send();

  }

  function cbalertContents(){
  alertContents(); 
  }
  function alertContents() {
    if (httpRequest.readyState === 4) {
      if (httpRequest.status === 200) {
        var resDataString = httpRequest.responseText;
        var resData = JSON.parse(resDataString);
        var msg = resData.msg;
        alert(msg);
      } else {
        alert('There was a problem with the request.');
      }
    }
  }
})();

My message.js is the following and i am trying to grab the msg attribute from the json string

var http = require('http');
var responseObject = { msg: 'Hello JSON.' };
var responseString = JSON.stringify(responseObject);
var body = new Buffer(responseString, 'utf-8');
exports.handle = function(req, res) {
  res.writeHead(200, {
    'Content-Type': 'application/json'
  });
  res.end(body);
};

Upvotes: 0

Views: 316

Answers (1)

Chickenrice
Chickenrice

Reputation: 5727

I don't think the callback implementation has any problem. You could try the implementation below if you want to use Node.js to generate JSON response.

var http = require('http');
var responseObject = {msg:"Hello JSON."};
var responseString = JSON.stringify(responseObject);
var body = new Buffer(responseString, 'utf-8');

http.createServer(function (req, res) { 
  res.writeHead(200, {'Content-Type': 'application/json',"Access-Control-Allow-Origin":"*","Access-Control-Allow-Headers":"X-Requested-With"}); 
  res.end(body); 
}).listen(1337, "127.0.0.1"); 
console.log("Node server is running");

You can remove "Access-Control-Allow-Origin":"*" and "Access-Control-Allow-Headers":"X-Requested-With" from response header if no Cross-Domain concern.

And update your ajaxButton click handler url parameter.

document.getElementById("ajaxButton").onclick = function() { makeRequest('http://127.0.0.1:1337/'); };

Start your node server (node message.js) and "Hello JSON" message will show as expected.

Screenshot:

enter image description here

Hope this is helpful.

Upvotes: 1

Related Questions