2

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.

2 Answers 2

1

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>
Sign up to request clarification or add additional context in comments.

10 Comments

Does this work if req.body.number in my code is coming from different html file?
I'm not sure I understand, can you elaborate?
If you look at the code above, my app.get is where the client types in the message which is index2.html. This is where I am getting req.body.number from. So can I get this same req.body.number in my ajax call? Sorry if this is confusing. Let me know if this clears anything up
Yes you should be able to. Can you add the code for index2.HTML so I can make an example?
@Baner made a quick edit, check it out and see if that works for you.
|
0

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);
        });
});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.