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 problem is that you want to send a response from the server, keep doing things on the server, and when you're done, send another response. This cannot be done with the 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 two-way communication open between the server and the connected clients, you should use a ws:// web socket protocol. If the operation you're running on the server isn't consuming too many resources or time, you can still use http and let the client hang and wait until the server completes its work and finally sends back the response. More information is needed in order to give you a more precise answer.
Web sockets surely suit your use case better, you can check out https://socket.io/ . If you still want to use a REST API, don't use the old xhr API, use a promise-based API, native fetch , or some library like axios that makes things much easier to manage.