0

I've been having trouble with front-end back-end interactions. I'm relatively sure I'm sending the data but I cannot access the data afterwards. Most recently I have used this code template (from mozilla's help pages a link ) to send the data. JavaScript:

function sendData(data) {
      var XHR = new XMLHttpRequest();
      var urlEncodedData = "";

  // We turn the data object into a URL encoded string
  for(name in data) {
    urlEncodedData += name + "=" + data[name] + "&";
  }

  // We remove the last "&" character
  urlEncodedData = urlEncodedData.slice(0, -1);

  // We URLEncode the string
  urlEncodedData = encodeURIComponent(urlEncodedData);

  // encodeURIComponent encode a little to much things
  // to properly handle HTTP POST requests.
  urlEncodedData = urlEncodedData.replace('%20','+').replace('%3D','=');

  // We define what will happen if the data are successfully sent
  XHR.addEventListener('load', function(event) {
    alert('Yeah! Data sent and response loaded.');
  });

  // We define what will happen in case of error
  XHR.addEventListener('error', function(event) {
    alert('Oups! Something goes wrong.');
  });

  // We setup our request
  XHR.open('POST', 'http://ucommbieber.unl.edu/CORS/cors.php');

  // We add the required HTTP header to handle a form data POST request
  XHR.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
  XHR.setRequestHeader('Content-Length', urlEncodedData.length);

  // And finally, We send our data.
  XHR.send(urlEncodedData);
}

HTML:

<button type="button" onclick="sendData({test:'ok'})">Click Me!</button>

My questions are: is there a better way of sending data (more suited to node)? and how can I access the data on the server side?

Charles
  • 50,943
  • 13
  • 104
  • 142
paulopolo
  • 3
  • 1

1 Answers1

0

is there a better way of sending data?

This is rather subjective question, but here is an alternative: you can create form with hidden elements and send them to the server using FormData(). This allows you also comfortable files processing:

<form onsubmit="xhrsend(event,this)" method="POST" enctype="multipart/form-data" action="http://ucommbieber.unl.edu/CORS/cors.php">
  <input type="hidden" name="myName" value="myValue"/>
  <input type="file" name="myFile"/>
  <input type="submit" value="Send"/>
  ...
</form>

use universal JS to XHR send any form

function xhrsend(ev,frm) {
  ev.preventDefault(); // prevent submiting form
  var XHR = new XMLHttpRequest();
  XHR.addEventListener(...); // whatever
  XHR.open('POST', frm.action, true);
  XHR.send(new FormData(frm)); // send form data
  this.reset(); // optional: reset form values
}

how can I access the data on the server side?

This question will guide you how to handle POST data on node.js server.

Note: if you play with node.js, I recommend to have a look at websockets - it can do more than XHR (like sending message from server to client).

Community
  • 1
  • 1
Jan Turoň
  • 31,451
  • 23
  • 125
  • 169