Access the binary information

Seeking assistance, can someone help me with this issue?

I have a basic Java servlet test displayed below:

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
         byte[] bytes = ReadWaveformAsBinary();

         response.setContentType("application/octet-stream");
         response.setContentLength(bytes.length);

         ServletOutputStream servletOutputStream = response.getOutputStream();

         servletOutputStream.write(bytes, 0, bytes.length);
         servletOutputStream.flush();
         servletOutputStream.close();
    }

This method is functional. It returns a byte array containing 10 double precision numbers. I have confirmed its functionality by calling it from a C# application:

public static bool CallWebServiceDownloadEndPoint(string szWebEndPoint, string szRequest, out double[] data)
        {
            data = null;

            bool bSuccess = true;

            WebClient webClient = new WebClient();

            try
            {
                byte[] byteData = webClient.DownloadData(szWebEndPoint + "?" + szRequest);
                Array.Reverse(byteData);

                data = CreateDoubleArrayFromByteArray(byteData);
                Array.Reverse(data);
            }
            catch
            {
                bSuccess = false;
            }

            return bSuccess;
        }

The resulting byte array has the expected length of 80 bytes (10 * 8 bytes) and the 10 numbers are accurate.

Now, my query is how can I invoke this Java servlet using JavaScript through an AJAX call?

For instance, in my attempt below, the alert message displays '19' instead of the expected '80':

function AJAXSendString(ajaxRequestObject, szURL, szParams, OnCallCompleted)
{
    if (ajaxRequestObject != null)
    {
        ajaxRequestObject.open("GET", szURL, true);

        ajaxRequestObject.responseType = "arraybuffer";

        ajaxRequestObject.onreadystatechange = function ()
        {
            if (ajaxRequestObject.readyState == 4)
            {
                if (ajaxRequestObject.status == 200)
                {
                    var arrayBuffer = ajaxRequestObject.response;

                    if(arrayBuffer)
                    {
                        var byteArray = new Uint8Array(arrayBuffer);

                        alert(byteArray.byteLength);
                    }
                }
            }
        }

        ajaxRequestObject.send(szParams);
    }
}

Your guidance on this matter would be greatly appreciated.

In another attempt to resolve this issue, I implemented the following changes but encountered the same result:

   function AJAXSendString2(ajaxRequestObject, szURL, szParams, OnCallCompleted)
    {
    if (ajaxRequestObject != null)
                    {
                        ajaxRequestObject.open("GET", szURL, true);

                        ajaxRequestObject.responseType = "arraybuffer";

                        ajaxRequestObject.onload = function(oEvent)
                        {
                            var arrayBuffer = ajaxRequestObject.response;

                            if(arrayBuffer)
                            {
                                var byteArray = new Uint8Array(arrayBuffer);

                                alert(byteArray.byteLength);
                            }
                        }

                        /*ajaxRequestObject.onreadystatechange = function ()
                        {
                            if (ajaxRequestObject.readyState == 4)
                            {
                                if (ajaxRequestObject.status == 200)
                                {
                                    var arrayBuffer = ajaxRequestObject.response;

                                    if(arrayBuffer)
                                    {
                                        var byteArray = new Uint8Array(arrayBuffer);

                                        alert(byteArray.byteLength);

                                        OnCallCompleted("1,-1,0,0,-1,1");
                                    }
                                }
                            }
                        }*/

                        ajaxRequestObject.send(szParams);
                    }

}

The alert still displays '19' rather than '80.'

Answer №1

When making a GET request, remember to include your parameters in the URL instead of the request body.

ajaxRequestObject.open("GET", szURL+'?'+szParams, true);

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

Learn the steps for inserting or updating data in a local JSON file solely through JavaScript

Currently, I am in the process of reading a JSON file and removing an element once it finds an exact match. My goal is to then push the remaining data back into the JSON file after deletion. readJsonFile("./objects.json", function(jsonData){ let parsedD ...

Creating a dynamic image slider that smoothly glides across a webpage

I've been working on a carousel (image slider) for my website and I need some help. Specifically, I want to reposition the entire slider slightly to the left on the webpage. You can see the slider in action on this site: and I also created a jsfiddle ...

What is the best way to use Promise.all() to delay the return of an array that is currently being constructed within the function?

In the following code block, I am trying to set an array as the value for a local variable by calling a function that returns an array. The issue arises because the Promises in the second function are not resolved until after the array has been returned to ...

Following a successful login, the User ID fails to store in the session

I am a beginner in the world of coding and I am currently working on one of my first apps. I have encountered an issue with my log in function. After user registration, the user id is successfully saved in the session object. However, it does not save into ...

Issue displaying JSON Object in React.js on the browser

I have been attempting to showcase a JSON object, comprising an array in React. Although I successfully composed the React code to achieve this, unfortunately, I am unable to view the output on my browser. Below is the snippet of my code: import React, { ...

When using JavaScript, I have noticed that my incremental pattern is 1, 3, 6, and 10

I am currently using a file upload script known as Simple Photo Manager. Whenever I upload multiple images and wish to delete some of them, I find myself in need of creating a variable called numDeleted (which basically represents the number of images dele ...

Choose a particular button using JavaScript and AJAX

In my Django app, users can save different items to a list. Each item has a corresponding delete button next to it. Currently, when I click on any delete button, it always selects and deletes the first item in the list. This is because my JavaScript code ...

Verify a roster within a display by utilizing annotations

My solution involves using a listbox to display a list as shown below, and I am also utilizing Chosen.js to allow for selecting multiple records. @Html.ListBox("AllLanguages", new SelectList(ViewBag.Languages, "Id", "Language1")) <div id="languagesDi ...

Are there any existing components for Wicket and SVG integration?

JavaScript allows control over SVG DOM, enabling AJAX functionality... I am curious about the availability of SVG components for Wicket and whether Wicket can output pure xml/svg format. A quick search revealed a question on Code Ranch. ...

Resolving the ExtJS4 and Spring MVC3 Error in Posting

I encountered the following error message: POST http://localhost:8080/mytest/admin/user/delete?_dc=1329102157683 415 (Unsupported Media Type) This error occurs when the EXTJS 4 Grid attempts to sync(). api: { read:'admin/user/list&apos ...

Alert: It is invalid for an <a> element to be nested inside another <a> element according to validateDOMNesting

I've been experimenting with using react-router in conjunction with reactstrap and create-react-app. While setting up the routing within my application, I encountered a need to utilize state for the reactstrap components. To achieve this, I converted ...

Chrome is experiencing a delay in closing the Select Option dropdown menu

On my webpage, I have two select option buttons placed on different tabs. Whenever one button is changed, I want to update the value of the other button and assign it to a specific element like a span in the example code provided. While everything works sm ...

Error in AngularJS: Failed to retrieve data using $http.post()

One of my current challenges involves: Transferring text data from HTML form text boxes to the Controller using ng-model and ng-submit directives. Sending this data from the controller to a Service. The Issue at Hand: - I am facing difficulties accessi ...

Emulating navigator.onLine in Node.js

I have recently started working on a Node.js application. To further my understanding of Node, I am developing a utility app for network detection purposes. Within this app, my primary objective is to determine: a) whether my computer is connected to the ...

Using jQuery to extract contact information from Google: A step-by-step guide

I'm currently using Google's API to access my contact list information and after logging the output in the console function fetch(token) { $.ajax({ url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token. ...

Challenges encountered with Material-UI elements

Attempting to implement the http://www.material-ui.com/#/components/drawer (Docked Example) component from Material-UI in conjunction with ReactJS. An error is encountered with the "=" sign in this line: handleToggle = () => this.setState({open: !this ...

Problem with hyperlinks: next character inadvertently added into the <a> tag in the TinyMCE user interface

I'm facing a challenge and struggling to come up with a solution. It could be due to incorrect setup or oversight on my part, but I suspect it might also be a bug. The issue is with the TinyMce setup applied in a Div (editable). setup: function (edi ...

Enable the entire button to be clickable without the need for JavaScript by utilizing a Bootstrap 5 button

Is there a way to make a button redirect when clicking anywhere on it, not just the text inside? Here is the button code utilizing Bootstrap 5: <button class="btn btn-rounded btn-primary" type="button">Placeholder Text</button& ...

Is it possible to utilize the @next/env package within the next.config.js file?

I'm looking to access the environment configuration from next.config.js in order to utilize some environment variables specified in .env.local and establish server runtime configurations based on them. Is it appropriate to use next.config.js for this ...

Which specific event in NextJS is triggered only during the initial load?

I am working on a NextJS app and I want to implement an initial loading screen that only appears during the first load. Currently, the loading screen pops up not only on the initial load but also whenever a link is clicked that directs the user back to the ...