Two ways to post data without reloading
Tags: html, javascript, webdev, beginners
Published: 2020-07-13 17:33:57

#INTRODUCTION
Today, I introduce to you two ways to POST data WITHOUT RELOADING. As you know, here *POST* means that of html method, i.e.
`<form action='/actionname' method='post'>`.
As you know again, the POST method reloads the page when the form is submitted. If the page includes some ajax part, it's cleaned up of course when submitted.
Basically, POST method is used to return a result, something like a login page, a mail form and stuff. In other words, POST method is supposed to have GET method which returns a next page.
However, we face and/or overcome some troubles like above sometimes.

The content of this post is based on my experience and the following codes are all verified already. However, the content is  not sophisticated and my English may often make you boring. But I believe that this gives you a new inspiration. This may be a treasure map for you.

#FIRST WAY: AJAX
This is a basic and simple way. Ajax is used to change a part of a page, e.g. search result. In such a case, Ajax utilises GET method.
```javascript
function functionname(){
  var ajax = new XMLHttpRequest();
  ajax.onreadystatechange = function(){
    if(this.readyState == 4 && this.status == 200){
      document.getElementById("ID").innerHTML = this.responseText;
    }
  };
  ajax.open("GET", "filename.html", true);
  ajax.send();
}
```
Similarly, Ajax has also POST method.
```javascript
function functionname(){
  var ajax = new XMLHttpRequest();
  var data = document.getElementById("ID");
  var formdata = new FormData(data);
  ajax.open("POST", "/actionname", true);
  ajax.send(formdata);
}
```
Let me explain. If you click an html element &lt;button onclick="functionname()">, some data a FORM element &lt;form id="ID"> has is sent to *server-side*. The point is that the usual GET and POST methods of HTML FORM correspond to the whole page, i.e. the URL, so the page is reloaded. On the one hand, those of AJAX correspond to only a part of the page, the page is not reloaded. For more precise details, XMLHttpRequest is googlable.

It is okay to write codes same as the case of usual FORM POST on server-side, but you don't need to write a redirect page anymore!

There is one more thing. Actually, it is seemingly better to write the following code which specifies the content type before "ajax.send()."
`ajax.setRequestHeader('Content-type', 'application/json; charset=utf-8');`
But I usually don't because it restricts the size of data.

#SECOND WAY: WebSocket
WebSocket is a technology (API) to give a duplex communication like a chat. If you are good at using WebSocket, this way may be an interesting trial. However, I'm sorry I can only write Socket.io which is JavaScript API!
```javascript
var socket = io();
function functionname(){
  var inputvalue = document.getElementById("ID").value;
  socket.emit('some name', inputvalue);
}
```
Let me explain. If you click an html element &lt;button onclick="functionname()">, the value of an html element <input id="ID"> is emitted to server-side. Just it! No reloading!
However, this way has a teeny, tiny, little problem. WebSocket is basically good at emitting a text, like a mail sending system. To emit others like an image file, you have to use MIME, I think. For more precise details, MIME is googlable.


#INTERESTING EXAMPLES
Let's implement the methods above. Examples include extra techniques but I believe it helps your web development to be more fantastic.
Firstly, the HTML for Ajax is here.
```html
<form enctype="multipart/form-data" id="formID">
  <input type="file" id="inputID" style="display:none" onchange="changefunction()">
</form>
<div id="divID"></div>
<button onclick="selectfunction()">SELECT</button>
<button onclick="postfunction()">POST</button>
```
The enctype is required to post a file and stuff. The point is the style of the input. How come we don't display the input? It is because the input with type "file" is nasty! So, our strategy is that we call the function of the input by clicking the SELECT button and display the selected file in the div element. The latter is done by *onchange*. And then, by clicking the POST button, we post the selected file to server-side and display a message in the div element because no action occurs after posting.
JavaScript which hears our grant is here.
```javascript
function changefunction(){
  document.getElementById("divID").innerHTML = 
  document.getElementById("inputID").value;
}

function selectfunction(){
  document.getElementById("inputID").click();
}

function postfunction(){
  var ajax = new XMLHttpRequest();
  var data = document.getElementById("formID");
  var formdata = new FormData(data);
  ajax.open("POST", "/actionname", true);
  ajax.send(formdata);
  document.getElementById("divID").innerHTML += "POSTED";
}
```
Let me explain two important things. One is that the .click() method can click any other elements and two that the var data must be set the FORM, not the input nor the div because the latter two have just the file name which is just a text.
Okiedok, we see the server-side. However, actually the server-side depends on your choice of a programming language. If you choose JavaScript and Express.js as a web framework, an example is here.
```javascript
app.post('/actionname', (req, res, next) => {
  var form = new formidable.IncomingForm();
  form.uploadDir = './directory';
  form.parse(req, (err, fields, files) => {
  if(err){
    next(err);
    return;
  }
  var oldPath = './' + files.inputname.path;
  var newPath = './directory' + "newname";
  fs.rename(oldPath, newPath, function(err){
    if(err) throw err;
    });
  });
});
```
Note that two modules are required: formidable and fs. The former can upload the selected file to the server. But the name is a random and save the file in a temporary folder. So, you need to rename it and move it to a folder you want using the latter. And one more thing. You need to add a name "inputname" to the input in the front-side for the "inputname" in the oldPath.


Next, let's implement the WebSocket version. Our goal is to display a message *locally*! A job of WebSocket is broadcasting. So in the usual method of it a message is globally emitted, i.e. everybody can see it without reloading. We want to send it to specific persons. Don't call this "waste", do call this "curiosity", please.
The HTML is here.
```html
<input type="text" id="inputID">
<div id="divID"></div>
<button onclick="functionname()">POST</button>

<span id="dummy" style="display:none;"></span>
```
The point is the "dummy" with style "diplay:none." Our strategy is as follows. The message emitted by clicking the button is firstly displayed in the dummy span. The message is globally emitted so everybody can see it. But the style of the dummy span interrupts it. And then, the innerHTML copies the message in the dummy span to the div element. The only one who clicked the button can see the message.
JavaScript is here. I'm sorry, this is for Socket.io.
```javascript
var socket = io();
var msg = document.getElementById("inputID").value;
socket.emit('socket name', msg);
setTimeout(function(){
  socket.on('socket back', function(backmsg){
    document.getElementById("dummy").innerHTML = backmsg;
    document.getElementById("divId").innerHTML = 
    document.getElementById("dummy").innerHTML;
  }
}, 100);
```
Conventionally the socket name uses two words, which is the sign between front- and server-sides. Anything can be set in the part of "msg" even if it's not needed. The response between front- and server-sides is done within 100 milliseconds.
The server-side JavaScript is here.
```javascript
socket.on('socket name', function(msg){
  io.emit('socket back', msg);
});
```
We notice that we use "socket.on" when we receive the message from the server-side. It has a function and anything can be set as its variable. There is no relation between the names of the variables in the server-side and the front-side, i.e. "msg" and "backmsg", they are just stamps when posting.
This fascinating or maybe cumbersome technique is interesting to be applied to information retrieval. We can do that after emitting a keyword to server-side, the data corresponding to the keyword and the "user" can only be emitted back to front-side.


#DISCUSSION
I introduce to you two ways to post data without reloading. One is to use Ajax and another is to use WebSocket. At present, due to lack of my knowledge, the former the better because all types of file can be handled. Anyway, the most important thing is "without reloading."
I like to use the latter, however. Because I believe that WebSocket is faster than (Ajax) POST because real-time response is required for WebSocket applications. But I don't know the truth. It is interesting to investigate which is best.

Thank you all for reading! Comments and *English corrections* are very welcome!

Safe journey!