0

I got the following code from here

I've tried this code with variable data being equal to 'test=yes' or with data being equal to {test:'yes'}

Here is the php script

if(isset($_POST['test'])){ 
   error_log("inside");
   echo "and I'd also like to return this";
};

And here is the nodejs piece of code:

function postToPHP(data, path){

    var httpreq = require('http');
    var querystring = require("querystring");
    var data = querystring.stringify(data);

    var options = {
        host : 'localhost',
        path : 'www' + path, //path is well defined in the actual code
        method : 'POST',
        headers : {
            'Content-Type' : 'application/x-www-form-urlencoded',
            'Content-Length' : data.length
        }
    };

    var buffer = "";

    var reqPost = httpreq.request(options, function(res) {

        res.on('data', function(d) {
            buffer = buffer+data;
        });
        res.on('end', function() {
           return buffer;
        });
    });

    reqPost.write(data);
    reqPost.end();

}

And the call of postToPhp

       //treat message?
        var message = "test=yes";
        //OR
        var message = "{test:'yes'}";

        var buffer = postToPHP(message,"path");
        console.log("buffer from PHP",buffer);

buffer is undefined

Nothing is shown in the error log and I assume something is not working with the code that I can't figure so I hope someone can help me figure this one out.

Community
  • 1
  • 1
extremeMeta
  • 93
  • 1
  • 1
  • 7
  • Remark: `res.on('end', function() { return buffer; });`- where do you think you return here to? actually that return value will be lost currently. – Sirko Nov 12 '14 at 16:05
  • Where is `postToPHP()` being executed? – casraf Nov 12 '14 at 16:24
  • You can't return a value from inside a callback function like this. Either you pass a callback to `postToPHP()`, which gets executed, when the data is received or you create a Promise from it. – Sirko Nov 12 '14 at 17:11
  • @Sirko could you exemplify please? And why is the script from php not called? – extremeMeta Nov 12 '14 at 17:14
  • Your post request seems fine. As for the other stuff have at look at this: http://stackoverflow.com/a/14220323/1169798 – Sirko Nov 12 '14 at 17:42
  • @Sirko actually the callback is defined in httpreq... and the script just doesn't get called because I can't log anything... – extremeMeta Nov 12 '14 at 17:53
  • @extremeMeta There is no callback defined to your `postToPHP()`, which is async as well ... And as I said - cant see any error in the request itself. – Sirko Nov 12 '14 at 18:20

0 Answers0