Reputation: 23
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);
}
});
Upvotes: 2
Views: 1067
Reputation: 5383
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
Upvotes: 4