0

How can I pass form input from client to server in javascript? Below is the client side. I want to take a username or anything entered in textbox, and send it to server.js where it will be processed for validation. the thing is that I need the data from client.js to be stored in a variable in server.js to be able o retreive it.

 var textbox;
 var dataDiv;
 window.onload = init;

function init(){
    textbox = document.createElement("input");
    textbox.id="textbox";
    dataDiv = document.createElement("div");
    var header = document.createElement("h1");
    header.appendChild(document.createTextNode("Select User"));
    var button = document.createElement("BUTTON");
    button.id = "myBtn";
    var textBtn = document.createTextNode("Click me");
    button.appendChild(textBtn);
    button.addEventListener("click", () => {
    sendData();
});

var docBody = document.getElementsByTagName("body")[0];//Only one body

    docBody.appendChild(header);
    docBody.appendChild(dataDiv);
    docBody.appendChild(textbox);
    docBody.appendChild(button);
}

function sendData(){
     var usrName = document.getElementById("textbox").value; //I want to send it to server.js
     var xhttp = new XMLHttpRequest();
     xhttp.onreadystatechange = function() {
     if (this.readyState == 4 && this.status == 200) {
           var dataObj = JSON.stringify(this.responseText);
           dataDiv.innerHTML = dataObj;
     }
 };
 xhttp.open("GET", "/register", true);
 xhttp.send();
}

This is the server side

 var express = require('express');
 var app = express();
 app.get('/register', handleGetRequest); //how do I pass usrName here?
 app.use(express.static('public'));
 app.listen(5000);

 function handleGetRequest(request, response){
      var pathArray = request.url.split("/");
      var pathEnd = pathArray[pathArray.length - 1];
      if(pathEnd === 'register'){
          response.send("{working}");
      }
      else
         response.send("{error: 'Path not recognized'}");
}
teddy
  • 27
  • 10
  • How can I extract data sent from client by using HandleGetRequest? – teddy Mar 21 '19 at 05:46
  • `\register` should be `/register` – Barmar Mar 21 '19 at 05:47
  • /register should be http://localhost:5000/register. Express (API) runs on different (5000) port, so you are having 404 error. – isidat Mar 21 '19 at 07:10
  • @isidat I am getting this error Uncaught TypeError: Cannot set property 'innerHTML' of null at XMLHttpRequest.xhttp.onreadystatechange (client.js:29) – teddy Mar 21 '19 at 07:19
  • @isidat wanted to know something. My only aim is to transfer data to server side. Can I use cookies? – teddy Mar 21 '19 at 07:38
  • @teddy Your current approach is correct. Cookies are client-side data only. – isidat Mar 21 '19 at 07:54
  • @teddy You trying to set innerHtml of an HTML element having id = data, however it doesn't exist. That is why you are getting that error. document.getElementById("data").innerHTML = responseData; – isidat Mar 21 '19 at 07:57
  • @isidat I changed the code and reviewed my javascript. Can I get some help on how to pass the usrName using xmlhttprequest on client side and to extract it on server side by handlegetrequest? – teddy Mar 21 '19 at 08:31
  • @teddy I have added the code in the answer section, it worked for me. If it works for you as well please check it as answer. – isidat Mar 21 '19 at 10:36

2 Answers2

0

If you use GET, you have to put the parameters in the URL.

xhttp.open("GET", "/register?usrName=" + encodeURIComponent(usrName), true);

See How to get a URL parameter in Express? for how you read the query parameter in Express.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • xhttp.send(...) always give error 404. Can you help me solve this out please? I am completely new to this. – teddy Mar 21 '19 at 05:50
  • If you're getting `404` error, then you haven't given the correct URL in `xhttp.open()`. – Barmar Mar 21 '19 at 05:51
  • I added my full code. I am still getting error 404. I really dont know how to proceed...please help me. – teddy Mar 21 '19 at 06:08
  • In the deleted answer you commented that the URL was `localhost:8000/register`. Express runs on the server, but `localhost` is the client. – Barmar Mar 21 '19 at 06:14
  • it a school project and we have to create a single web page using localhost. What is the server address supposed to be? – teddy Mar 21 '19 at 06:18
  • Are you running node.js on the same machine as the browser? – Barmar Mar 21 '19 at 06:19
  • yes I am using node.js + express. XAMPP appache and mysql. Webstorm as IDE – teddy Mar 21 '19 at 06:21
  • I'm not sure why it's not working then, but I don't really know node.js+Express well. – Barmar Mar 21 '19 at 06:21
  • The question was about how to send the parameter, that's all I was answering. This is a completely different problem, you should ask another question. – Barmar Mar 21 '19 at 06:22
  • can you please check the code I added. I just want to pass usrName to server,js. please help me – teddy Mar 21 '19 at 08:36
0

Sending data:

function sendData(){
  var usrName = document.getElementById("textbox").value; //I want to send it to server.js
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
      if (this.readyState == 4 && this.status == 200) {
          var dataObj = JSON.stringify(this.responseText);
          dataDiv.innerHTML = dataObj;
      }
  };
  xhttp.open("GET", "http://localhost:5000/register?usrName=" + encodeURIComponent(usrName), true);
  xhttp.send();
}

Reading data:

function handleGetRequest(request, response){
  var urlParts = request.url.split("?");
  if(urlParts[0] === '/register'){
      var usrName = urlParts[1].replace('usrName=', '');
      response.send("{" + usrName + "}");
  }
  else
    response.send("{error: 'Path not recognized'}");
}
isidat
  • 936
  • 10
  • 18