0

I would like to send let's say 2 variables to node js server. I know how to do it with one... But if I want to send two datas, which could be separately read in node and then written into xml file the method I used doesnt work.

http.createServer(function (req, res) {
if (req.method === "POST") {
    req.on('data', function (data) {
        requestData += data;
        console.log(data.toString());
        fs.appendFile('name.xml','<XML>' +  data + '\n</XML>', function (err) {

    });

});

}

That was node js code sample how I get data from ajax call.

var info2value = $('#edittocatch').val();
var colorvalue = $('#catchColor').val();
 $.ajax({
                type: "POST",
                url: 'http://127.0.0.1:5073/',
                data:  info2value

            });

And now what should I do to send data2 data3 etc?

1
  • data should be sent as key/value pairs Commented Sep 15, 2014 at 14:30

2 Answers 2

1

Use an object as the value of the Ajax data property, adding the variables as property values:

$.ajax({
  type: "POST",
  url: 'http://127.0.0.1:5073/',
  data: { info2value: info2value, colorvalue: colorvalue }
});

As for NodeJS, you would use url and querystring to parse the URL into an object that you can access with the usual dot notation.

var url = require('url');
var querystring = require('querystring');

http.createServer(function (req, res) {
  var urlObj = url.parse(req.url);
  var qs = querystring.parse(urlObj.query)

  // access the URL parameters with dot notation eg: qs.infoValue2
});

url.parse will give you something like:

{ protocol: 'http:',
  slashes: true,
  auth: null,
  host: '127.0.0.1:5073',
  port: '5073',
  hostname: '127.0.0.1',
  hash: null,
  search: '?info2value=moose&colorvalue=red',
  query: 'info2value=moose&colorvalue=red',
  pathname: '/',
  path: '/?info2value=moose&colorvalue=red',
  href: 'http://127.0.0.1:5073/?info2value=moose&colorvalue=red' }

And from there querystring.parse on the query property of that object will give you:

{ info2value: 'moose', colorvalue: 'red' }
Sign up to request clarification or add additional context in comments.

1 Comment

It's been a while since I've done any nodeJS but this will probably do what you need it to.
0

Ok I handled it with Data.split(" "). It creates array with seperate strings.

Comments

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.