i've been given the task to do a website with HTML/CSS/JS and have 3 buttons that when clicked sends a code like "10", "01" and "11" to a c++ program. The c++ program is expected to send back a response and do a function depending on the code it receives. Send some data to the website and the website should give a response back to the c++ program.
I'm pretty new to Ajax and i'm trying to understand if this is the right path for the both party to communicate with each other.
for now i did this in HTML:
<button class="btn" id="btnfront" onclick="sendfrontimg()">front</button>
<button class="btn" id="btnback" onclick="sendbackimg()">back</button>
<button class="btn" id="btnboth" onclick="sendbothimg()">both</button>
and in the Javascript file (for one button):
function sendfrontimg() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}
and this part for the callback function to have a response from the server:
function sendfrontimg(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.onload = function(){ // When the request is loaded
callback(httpRequest.responseText);// We're calling our method
};
httpRequest.open('GET', "/echo/json");
httpRequest.send();
}
is this right so far?
Your main issue is that you want to send back a response from server, keep doing stuff on server, and when done, send back another response. This can't be done with http protocol, since the default behavior of HTTP/1.0 is to open a separate TCP connection for each HTTP request/response pair. So once the server sends a response to an http call, the "conversation" is closed. If you want to keep a bidirectional communication open between server and connected clients, you need to use a web-socket protocol ws://.
If the operation you are executing on server is not too much resource and time consuming, you could keep using http, and let the client hang and wait until the server completes to execute its job, and finally send the response back. More info are needed to be able to give you a more accurate answer.
Web sockets surely fit best your use case, you can check https://socket.io/.
If you still want to use a REST API, do not use the old xhr API, use promise based API, native fetch or some library like axios which make things much easier to manage.