Home > OS >  How to read the user input on the client-side, modify it with JS on the client-side, and then POST i
How to read the user input on the client-side, modify it with JS on the client-side, and then POST i

Time:04-29

Problem: I want to read a user input on the client-side, do some processing on the variable using JavaScript, still on the client-side, then POST the modified variable to the server-side (Node.js). Research: There are a few similar questions on Stackoverflow, but the answers are not the questions to my requirement. I read about Ajax and Fetch, but they focused on collecting info from the server rather than sending a JS variable from the client-side to the server. I am not sure about using WebSockets for such a simple task.

Code: The following code is in an EJS template. I want to POST variable name to Node.js in the following code:

<body>
    <div>
        <label for="name">Name: </label>
        <input id = "name" type="text"> <br><br>
        <label for="name">City: </label>
        <input id = "city" type="text"> <br><br>
        <button id="submit">Submit</button>
        <button id="capitalize">Capitalize Everything</button>
        <button id="clear">Clear</button>
    </div>

    <p>
        Your name is <span id="outputName">____</span>. The city in which you live is <span id = "outputCity">____.</span>
    </p>


    <script>
        var submit = document.getElementById("submit");
        submit.onclick = () => {
            var name = document.getElementById("name").value;
            var city = document.getElementById("city").value;
            name = " "   name //some processing on varibale name, can be anything else
            document.getElementById("outputName").innerText = name;
            document.getElementById("outputCity").innerText = city;
        }   
    </script>

    <form action="/posty" method="post">
        <label for="verse"></label>Search The Bible <br></label>
        <input type="hidden" id ="id" name = "name" value = "name">
        <button type="submit">Submit</button>
    </form>
    
</body>

The related serverside code:

app.post('/posty', (req,res) => {
    console.log(req.body.name)
})

In the following:

<input type="hidden" id ="id" name = "name" value = "name">

what is transferred to the server is the string "name" , not the content of the JS variable name. I tried to put the name between <%= %> as it was an ejs template, but it didn't work.

Problem Summary: How to read the user input on the client-side, modify it with JS on the client-side, and then POST it to the sever-side (Node.js)?

Thank you

CodePudding user response:

You should use Ajax to Post data to your route (/posty).

$(document).on("click", "#submit", function () {
  
          var name=$('#name').val()
          var city =$('#city').val()
          var outputName=$('#outputName').text('name')
          var outputCity=$('#outputCity').text('city')
          var id= $('#id').attr('id')
          
          var obj=JSON.stringify({
            name:name,
            city:city,
            id:id,
            outputName:outputName,
            outputCity:outputCity
       })

 
        $.ajax({
          type: "POST",
          url: "/posty",
          data:obj,
          contentType: "application/json",
          beforeSend:function(){
         //can put some spinner,before request
          },
          success: function (res) {
            //respond from Backend
            
            if(res){
          ...
            }
          },
        });
      });



//On server side

  app.post("/posty", urlencodedParser, async (req, res) => {
    try {
      await db.query(...);
          res.send(true);
    }
      } catch (err) {
      console.log(err);
    }
    })

Sorry for Jquery,its easier to write..

CodePudding user response:

You should specify the name attribute correctly of each input, so that you can send a HTTP POST request with the payload you want.

<body>
  <form action="/posty" method="post">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">
  
    <button type="submit">submit</button>
  </form>
</body>

If you want to modify the input value before sending the request, you can define a custom function, modify input value in it, and use the native fetch API to send it.

<body>
  <script type="text/javascript">
    function customSubmit() {
      const name = document.getElementById('name').value   ' mock';
      const city = document.getElementById('city').value   ' mock';
      fetch('/posty', {
        method: 'POST',
        body: JSON.stringify({ name, city })
      })
    }
  </script>
  <form onsubmit="event.preventDefault(); customSubmit()">
    <label for="name">Name: </label>
    <input id="name" name="name" type="text">

    <label for="city">City: </label>
    <input id="city" name="city" type="text">

    <button type="submit">submit</button>
  </form>  
</body>
  • Related