Click handler that transmits data to a server using ajax

I have been tasked with creating a website using HTML, CSS, and JavaScript that includes three buttons. When clicked, these buttons will send codes such as "10," "01," and "11" to a C++ program. The C++ program will then respond and perform a function based on the code it receives. Data will be sent from the website, and the website should return a response to the C++ program.

As someone new to Ajax, I am trying to determine if this is the correct approach for enabling communication between both parties.

Currently, in HTML, I have implemented the following:

<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>

Additionally, 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 a portion for the callback function to receive a response from the server:

function sendfrontimg(callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onload = function(){
       callback(httpRequest.responseText);
    };
    httpRequest.open('GET', "/echo/json");
    httpRequest.send();
}

Is this implementation on the right track?

Answer №1

The main challenge you're facing is the need to send a response from the server, continue processing on the server, and then send another response. This isn't possible with the HTTP protocol because HTTP/1.0 by default creates a new TCP connection for each HTTP request/response pair. Once the server responds to an HTTP call, the communication is terminated. To maintain ongoing communication between the server and connected clients, you should consider using a WebSocket protocol like ws://.

If the server operation isn't too resource-intensive or time-consuming, you could continue using HTTP and have the client wait for the server to finish its task before receiving a response. More details are necessary for a more precise solution.

WebSockets are ideal for your scenario; you can explore resources like https://socket.io/. Alternatively, if you prefer to stick with a REST API, avoid using the outdated XHR API and opt for a promise-based API like native fetch or a library such as axios, which simplifies the process.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

When converting to .glb format, the material becomes invisible unlike in .gltf files

After exporting a model using the glTF exporter in Blender 2.8, I noticed that when exporting to .glb format, the texture is no longer visible. Strangely, when I view the .glb file in the glTF Viewer from it appears fine, but in my environment and in the ...

Is it possible for a nodejs server to handle both grpc and express servers simultaneously, or do they need to be separate servers?

I'm currently in the process of building a REST server using Node/Express. I'm curious about how to incorporate a GRPC server within the same setup. Would it be possible to run both servers on the same NodeJS instance, or is it recommended to hav ...

Error with Vimeo SDK: Mysterious Player Issue Post Setup (VueJS)

I have a requirement to showcase multiple videos on a Vue-powered website using a Vimeo player. To achieve this, I have developed a VideoPlayer component specifically designed for each video: <template> <div class="video-element__containe ...

How to trigger a JavaScript function using a button click

I've been struggling to figure out why my JavaScript code isn't functioning properly within Ionic. Can anyone guide me on how to store a number in a variable, display that variable, and increment it when a button is clicked? I have successfully ...

Combining Rxjs map and filter to extract countries and their corresponding states from a JSON dataset

I have a unique dataset in JSON format that includes information about countries and states. For example: { "countries": [ { "id": 1, "name": "United States" }, { "id": 2, "name": "India" }], "states": [ { ...

Checking forms for standard regulations with jQuery

Within my project, I have implemented multiple forms, where each form shares common fields like email, but also contains its own unique fields such as uniqueFieldA for Form A and uniqueFieldB for Form B. The challenge at hand is to develop a set of valida ...

How can one extract information from memory with Vowpal Wabbit?

Is there a method to input data for model training in Vowpal Wabbit without saving it to disk? Here's my scenario: I have a sizable dataset in csv format (around 2gb) that can be easily loaded into memory. I import it into R as a data frame and then ...

Attempting to minimize the repetition of code in Redux by implementing some utility functions

Is there a potential issue with the method I'm attempting in this URL: The concept involves altering only the actions file when introducing a new action. One improvement I am considering is recursively merging the status passed from the actions with ...

Iterating Through Multiple Dimensions

I am facing a challenge with creating rules from three arrays that I have. The task is to generate every possible combination of entries from each array, but I am struggling with the logic required to write a function for this purpose. For example: var ar ...

Struggling to retrieve JSON data from the MercadoLibre API while consistently encountering the CORS error?

I have been attempting to access a mercadolibre API that provides JSON data I need to utilize. However, whenever I make an AJAX GET request, I keep receiving the same error: "Response to preflight request doesn't pass access control check: It does n ...

Filtering input based on its occurrence rate (enable/disable debounce)

Utilizing node on a raspberry pi and the module onoff to capture input. I am interested in running function B only if function A is triggered twice within one minute. var gpio = require('onoff').Gpio; var sensor = new gpio(7, 'in', &ap ...

Error in Next.js Image Component: Missing SRC

Encountering an error with the next.js image component, specifically related to a missing "src" property. Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` component. Received: {} Th ...

Get a specific attribute of an object instead of directly accessing it

Is there a way to retrieve a specific object property in my checkForUrgentEvents method without referencing it directly? I attempted using Object.hasOwnProperty but it didn't work due to the deep nesting of the object. private checkForUrgentEvents(ur ...

"Utilizing jQuery, Ajax, and the powerful REDIRECT_QUERY_STRING feature

Recently, I decided to revamp a small website consisting of three or four pages using a minimalist MVC framework (which might be excessive, but I wanted to experiment). The site is configured with an .htaccess file: RewriteEngine on RewriteCond %{REQUE ...

The underscore (_) parameter in HTTP GET requests

Lately, I've been seeing the '_' parameter on many websites with a seemingly random string attached to it. For example: website.com/?_=98765432 Can someone explain the significance of this parameter and how these numbers are generated? ...

Tips on incorporating a color picker in HTML using jQuery

Looking to implement an HTML color picker with the help of JQuery. Wondering if there is a simpler method to do this without relying on external JQuery libraries? Experimented with <input type="color"> but encountered issues that prevented it from ...

The most basic method for monitoring changes in an object

An application needs to immediately update all clients with a large object when it changes. What is the most basic method to monitor changes in a Node.js object? Consider the following object: var obj = { num: 3, deep: { num: 5 } } A functi ...

Node.js and Azure blob storage compliment each other perfectly

After utilizing Azure DB for some time, I encountered an issue where I couldn't store large files in Azure. As a workaround, I discovered Storage Account. I have been using tedious (JS) to make queries. Is it possible to save and retrieve data using ...

What is the process for generating a "See More" button for the hidden outcomes of a mySQL query?

I've implemented a search engine on my webpage using PHP. Currently, all the results are displayed on a single result page. To improve user experience, I am now looking to limit the number of results to 20 per page and add a "Next Page" link... If I ...