Khan Saab
Khan Saab

Reputation: 511

How to send form data to server

I want to build a small website. I have backend almost done but i can't find how can i send form data to server. Here is my attempt and i want to send the data to localhost running at port 3000 for example:

jQuery('#signUp-Form').on('submit',function(e){
    e.preventDefault();
    console.log('Sending data');
    var name = jQuery('[name = username]').val();
//    socket.emit('sign-up',{
//      username: jQuery('[name = username]').val(),
//      password: jQuery('[name = password]').val()
//    });
});

I can do with socket.io but however i want to use POST,GET etc and at server side i built my server with express.

I can retrieve the name from the field into the var name and now i want to send it to server: here is the function which will handle this request. Only first two lines:

app.post('/login',(req,res) => {
  var body = _.pick(req.body, ['username', 'password']);

Now my question is how can i send data in such format so that '/login' matches with pattern and req.body contains the name only.

It is the basic question but i don't see anywhere how can i do this.

Upvotes: 2

Views: 8479

Answers (1)

Rafael
Rafael

Reputation: 7746

Khan, it looks like you are attempting two methods of form submission: non-AJAX and AJAX. From your question it's not apparent which method is intended, but I will show both methods:

Non-AJAX

Using <form action="/login" method="POST">:

<form id="myform" action="/login" method="POST">
    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit">login</button>
</form>

This method will refresh the page and make a POST request to /login sending the url encoded data like:

username=nha&password=asonteu

AJAX

With AJAX, the page won't refresh, and you must send the data programmatically:

$( "#myform" ).on( "submit", function( event ) {
    event.preventDefault();
    let data = $( this ).serialize();
    //make our request here
    $.post( "/login", function( data ) {
        console.log(data);
    });
});

serialize() also url encodes the form data.

Your server must handle any expected data format (to extract the fields properly). URL encoding is useful, but later you will see JSON or perhaps protobufs. It really doesn't matter which format you use as long as both the client and server agree.

NOTE: With POST, the data will be in the request body

I hope this helps!

Upvotes: 3

Related Questions