2

I've learnt dealing with ajax calls to exchange information from the server to the browser but now I'm having big troubles converting my code to a server-side node compatible JS using http requests. I've read different tutorials but I just can't adapt them to my code. My simple JS / jQuery function is this:

function ajaxCall(data, php, callback) {
    ax = $.ajax({
        type: "POST",
        data: data,
        url: php,
        success: function (raw_data) {
            f = $.parseJSON(raw_data);
            callback(f);
        },
    });
}

And I need to convert it to a pure JS version with http requests to use with node.js. Thanks for any help.

EDIT: I tried and tried, but without success. Here is the code I used, I just get lots of meaningless words on my console.log, perhaps you can correct it:

Version 1

var data = {"action": "update", "tN": 2155};
var request = require("request");

request.post({
    url: 'http://example.com/PHP.php',
    data: data,
    }, function(error, response, body){
    console.log(body);
    }
);

Version 2

var request = require("request");
var options = {
    method: 'POST',
    uri: 'http://example.com/PHP.php',
    data: {"action": "update", "tN": 2155},
};    
request(options, function(error, response, body) {
    if(error){
        console.log(error);
    }else{
        console.log(response);
    }
});
5
  • EDIT: And I do not want to use the jquery module in node.js (it's very problematic, especially on Windows!) Commented Jan 18, 2015 at 17:06
  • So you don't really want ajax, you just want to make a request from the server? Commented Jan 18, 2015 at 17:07
  • npmjs.com/package/xhr2 Commented Jan 18, 2015 at 17:08
  • github.com/request/request Commented Jan 18, 2015 at 17:08
  • If you don't want XHR but only need to make a http request look here stackoverflow.com/questions/25652057/… Commented Jan 18, 2015 at 17:10

1 Answer 1

4

Use request.js

Example:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Show the HTML for the Google homepage.
  }
})

Documentation request.js

Sign up to request clarification or add additional context in comments.

2 Comments

mhh ok yes thank you, that would definitely be useful, but I'd like if possible to avoid using libraries, I thought converting that simple function may produce simple JS as well...I'm also interested in "seeing" the pure JS that does that http request, just for curiosity, if you know what I mean!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.