U
U
UNy2018-07-29 01:03:09
Node.js
UNy, 2018-07-29 01:03:09

Sending a form to the server and getting data back?

Sending the form to the server:

<form action="http://localhost:3000/add" method="post" id="myform">
    <input type="text"  value="" placeholder="username" id="login-name" name="name">
    <input type="password"  value="" placeholder="password" id="login-pass" name="password">
    <button type="submit" class="btn btn-default">ВХОД</button>
</form>


I get it on the server:
app.post('/add',urlencodedParser,function (req,res) {
  console.log(req.body);
});

How to send with Ajax? So that I can send the form data back from the server and display it.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
U
UNy, 2018-07-29
@UNy

Managed to do it this way:

<form id="myform">
    <input type="text"  placeholder="username" id="login-name" name="name">
    <input type="password"   placeholder="password" id="login-pass" name="password">
    <input type="button" id="formsub" value="Вход">
</form>

<div id="tester"></div>
<script>
    let myButton = document.getElementById('formsub');
    myButton.addEventListener('click',function (ev) {
        let name = document.forms['myform'].elements['login-name'].value;
        let pass = document.forms['myform'].elements['login-name'].value;

        let obj = {
            name:name,
            pass:pass
        };
        fetch('/add', {method: 'POST',body:JSON.stringify(obj),headers:{'content-type': 'application/json'}})
                .then(function (response) {
                    return response.json();
                })
                .then(function (data) {
                    let us = document.createElement('h2');
                    us.innerHTML = data.name;
                    let mydiv = document.getElementById('tester');
                    mydiv.appendChild(us);
                })
                .catch(alert);
    })
</script>

A
Anatoly, 2018-07-29
@trofimovdev

The answer is easily found by a search engine.

var data = $('#myform').serialize();
$.ajax({
   type: "POST",
   url: "http://localhost:3000/add?",
   data: data,
   success: function(msg) {
     alert(msg);
   }
 });

And don't forget to add a response function to the server.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question