Baner
Baner

Reputation: 51

How to send data to post method of node js using AJAX/jQuery?

I have a udp server that sends back different message each time a message is sent to it. If i hard code the 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.

Upvotes: 2

Views: 1162

Answers (2)

Nam Le
Nam Le

Reputation: 329

modified a little bit code from wrxsti, We don't need to let a var formdata, just use:

$("#submit").on("submit",function (e) {
        e.preventDefault();
        $.post("http://localhost:5000/post/comment",$(this).serialize(), function( data ) {
          console.log(data);
        });
});

Upvotes: 0

wrxsti
wrxsti

Reputation: 3504

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

JSON:

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

URL:

$.post('/output2?number=value1', function(data){
    // Do things
});

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

app.post('/output2', function(req, res){
    var number = req.body.number;
    // Do things
});

The way you have your form set up you don't really need jQuery post method to do this. If you did want a full jQuery submission though, add this to your index2.html.

<script>

$(function(){
    $(document).on('submit', 'form', function(e){
        e.preventDefault();
        var formdata = { number: $('input[name="number"]').val() };
        $.post('/output2', formdata, function(data){
            alert(data);
        });
    });
});

</script>

Upvotes: 1

Related Questions