Baner Baner - 5 months ago 20
Node.js Question

Can you send data to post method of node js using AJAX/jQuery

app.post('/output2', function(req, res){
//Send UDP packet continuously every ten seconds
var HOST= '192.168.0.136';
var PORT= 69;
var number= req.body.number;
//Reading in the user's command, converting to hex
var message = new Buffer(number, 'hex');

//Sends packets to UDP

client.send(message, 0, message.length, PORT, HOST, function (err, bytes) {
if (err) throw err;
});


client.once('message', function (message) {
var val = message.toString();
console.log(val);
res.render('index', {val:val});
});
});


request

$(function() {
$('#loadRequest').click(function() {
$.post('/output2',function(res) {
$('#myDiv').html(res);
});
});
});


I have a udp server that sends back different message each time a message is sent to it. If i hard code the a message into the var message, then everything works. But i want the client to able to manually type in a message, then when the refresh button is pressed, the ajax re sends that same inputted message again. Right now, nothing happens when the button is pressed because ajax doesn't know what req.body.number is.

Answer

You can use jQuery's $.post() method to send a json object, or you can url encode parameters:

JSON:

$.post('/output2', {parameter1: 'value1', parameter2: 'value2'}, function(data){
    // Do things
});

URL:

$.post('/output2?parameter1=value1&parameter2=value2', function(data){
    // Do things
});

To receive these parameters on your post route you can use the req.params variable:

app.post('/output2', function(req, res){
    var param1 = req.params.parameter1;
    var param2 = req.params.parameter2;
    // Do things
});