0

I have a page with two text areas, and I want to submit the data from one of them to node (using ajax), node then does some processing, and then returns the response which is then populated into the second text area.

The console log shows that the node code is working fine it gets to res.end() but the ajax keeps reporting an Error or a TimeoutError, instead of invoking the success callback method.

The key parts of the code are:

frontend

<script>
      function processClick() {

          var data = {};
          data.topic = document.getElementById("topic").value;
          data.message = document.getElementById("request_area").value;

         $.ajax({
              url: 'http://localhost:8888/',
              dataType:'json',
              type: 'POST',
              data: JSON.stringify(data),
              timeout: 2000,
              success: function(data) {
                   $("#response_area").append(data);                            
              },
              error: function(jqXHR, textStatus, errorThrown) {
                   $("#response_area").append('[Error[textstatus=' + textStatus + ',errorThrown=' + errorThrown + ']]');
              }
         });
      }

</script>

Node

var port = 8888;
var http = require('http');


http.createServer(function (req, res) {
    response = null;
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'application/json'});

    res.end('{a:"b"}');

}).listen(port);

console.log("listening on " + port);

I've stripped out most of what node does, and tried to get it just to return a json string {a:"b"} but that too results in errors. Am I messing up the content types? How much of an impact would that have?

Any help would be appreciated.

Bart
  • 26,399
  • 1
  • 23
  • 24
Kash.
  • 242
  • 1
  • 3
  • 15
  • 1
    JSON properties must be in quotes. Try `res.end('{ "a": "b" }');`. Actually, try `JSON.stringify({ a: "b" });`, that's really the way to produce JSON objects. – Bart Apr 27 '13 at 02:49
  • Thanks for the correction, but unfortunately, it results in the same error. – Kash. Apr 27 '13 at 03:07
  • 1
    What happens if you simply visit the page in your browser? What error do you receive? – Bart Apr 27 '13 at 10:32

2 Answers2

1

The way you are making request is actually a cross domain request and violating same origin policy, therefore the jQuery ajax calls are failing. To get this working cross-domain you should use JSONP based format.

For example node.js code:

var port = 8888;
var http = require('http');


http.createServer(function (req, res) {
    response = null;
    console.log('request received');
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end('_testcb(\'{"a": "b"}\')');

}).listen(port);

console.log("listening on " + port);

and the client side javascript should be like this

<script>
      function processClick() {

          var data = {};
          data.topic = document.getElementById("topic").value;
          data.message = document.getElementById("request_area").value;

         $.ajax({
              url: 'http://localhost:8888/',
              dataType:'jsonp',
              type: 'POST',
              jsonpCallback: "_testcb",
              data: data,
              success: function(data) {
                   $("#response_area").append(data);                            
              },
              error: function(jqXHR, textStatus, errorThrown) {
                   $("#response_area").append('[Error[textstatus=' + textStatus + ',errorThrown=' + errorThrown + ']]');
              }
         });
      }

</script>

The best way to do this within same domain is by using express. If you have to do this in pure nodejs without using express framework then you can check out the below link.

https://stackoverflow.com/a/6012543/517525

This also gives you detailed explanation about your query.

Community
  • 1
  • 1
naquiuddin
  • 1,000
  • 2
  • 12
  • 25
  • Thanks andyfan. When Blender mentioned cross-origin requests I looked it up, and amended my code and was just about to change the revised version when I saw your post: and it is almost a mirror. Thanks for your help and your explanation. – Kash. Apr 27 '13 at 12:45
0

Your JSON string is invalid. The keys need to be quoted:

{"a":"b"}

Or:

JSON.stringify({a: 'b'})
Blender
  • 289,723
  • 53
  • 439
  • 496