What is the best way to trigger an ajax function whenever the servlet undergoes a change?

I am looking to dynamically enable or disable a button based on the insertion or removal of a USB device. How can I utilize ajax to update the button status whenever a USB is detected?

Using Ajax

function checkUSBStatus(){
var xmlhttp;
if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest();
}
else
{
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}

xmlhttp.onreadystatechange=function()
{
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
            alert (xmlhttp.responseText);
            if(xmlhttp.responseText == "true") {
                document.getElementById('scan').disabled=false;
            }
            else {
                document.getElementById('scan').disabled=true;
            } 

        }
}
xmlhttp.open("GET", "CheckUSBStatusServlet", true);
xmlhttp.send();
}

Sending Response to JSP from Servlet: Is there a way to trigger an event listener each time and resend the response back to JSP to execute the ajax function again?

    public static boolean usbConnected = false;

protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, IOException {
    // TODO Auto-generated method stub
    //super.doGet(req, resp);       

    PrintWriter out = resp.getWriter();

    RemovableStorageEventListener listener = new RemovableStorageEventListener() 
    { 
        public void inserted(Storage storage) {
            usbConnected = true;
    }
        public void removed(Storage storage) {
            usbConnected = false;
        } 
    }; 

    BundleContext bc = AppManager.getInstance().getBundleContext();
    StorageManager sm = StorageManager.getInstance(KSFUtility.getInstance().getApplicationContext(bc));
    sm.addListener(listener);

    if (usbConnected == true)
    {
        out.print("true");
    }
    else
    {
        resp.reset();
    }

}

Answer №1

To specify the content type as JSON, use

response.setContentType("application/json");
. You can then generate the output in JSON format by creating a string like this: {"status", "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

Issues with rendering AngularJS onto an HTML page are currently being experienced

I was attempting to learn AngularJs in order to improve my front-end development skills, but unfortunately I ran into some issues. Despite following the video tutorials on their site step by step, I couldn't get it to render correctly. Here's the ...

``There is a pesky jQuery bug causing the page to unexpectedly refresh upon submitting an

Having issues with AJAX form submission. Here is a snippet of the code: $("#content").html("<form id='requestInfo'>............</form"); This code places a form inside a div with an id=content. Another piece of the code: $("#request ...

Arrange the elements in the array based on their parent relationships (using topological sort) and their importance within

My array contains objects with elements that are dependent on each other. To properly store this data in a database, I need to order the array by importance (based on parent dependency) and update all children's parent property with the corresponding ...

Utilizing HTML's multiple input type color feature to save selected colors directly to the database

I am currently using the input type color to select colors for customizing my site. I save the selected color to a database and then retrieve it to apply it to different areas of the site. This works well for a single input type color, but now I have mul ...

Can you assist me in producing a family tree using a binary search tree?

I recently delved into the world of binary search trees and tackled an exercise that required me to construct a family tree using a binary search tree. Although I managed to create the tree, I encountered some issues along the way. This particular family ...

Is there a way to use lodash to convert an array into an object?

Below is an array that I am working with: const arr = [ 'type=A', 'day=45' ]; const trans = { 'type': 'A', 'day': 45 } I would appreciate it if you could suggest the simplest and most efficient method to ...

Inquiries regarding scopes, node.js, and express

I struggle with understanding scopes and similar concepts in various programming languages. Currently, I am working on an express application where I take user input, query an arbitrary API, and display the results in the console. To interact with the REST ...

Insert a clickable element within an HTML document

I have an idea for a questionnaire that includes questions and an interactive element at the end. At the completion of the questionnaire, there will be a button labeled "display answers" which users can click to reveal the correct responses. For example, ...

A guide on displaying data in a table using a select dropdown in a pug file and passing it to another pug file

After creating a single page featuring a select dropdown containing various book titles from a JSON file, I encountered an issue. Upon selecting a book and clicking submit (similar to this image), the intention was for it to redirect to another page named ...

What is the best way to include an onClick event on a hyperlink enclosed within a string?

I am trying to wrap an anchor tag within a string. export function linkify(inputText) { const replacePattern = /(\b(https?|ftp):\/\/[-A-Z0-9+&#/%?=~_|!:,.;]*[-A-Z0-9+&#/%=~_|])/gim; if (replacePattern.test(inputText)) { input ...

Utilizing callback functions with JSONP in jQuery

Utilizing jQuery scripts to fetch a JSON feed from Flickr and YouTube in order to dynamically generate HTML on my WordPress website is the current approach I am taking. To pull data from Flickr, I am using: <!-- Script for retrieving photos from Flickr ...

In React JS, the data from my response is not being saved into the variable

My goal is to store the response data in the variable activityType. Within the useEffect function, I am iterating over an API based on the tabs value. The API will return a boolean value of either true or false. While I can successfully log these values ...

Characteristics of a Content Management System (CMS) and frameworks

While Content Management Systems are well-known, what key elements must an application have in order to qualify as a genuine CMS? Additionally, which Java frameworks are suitable for creating one? ...

Guidelines for setting up a universal Handler using React and AXIOS

In my current project, I am utilizing ReactJs and AXIOS. My goal is to implement a global error handler without having to add a catch statement to each request throughout the codebase. To achieve this, I have created a service that consolidates all request ...

The issue of jQuery .hover malfunctioning on dynamically loaded AJAX elements

After making an AJAX call, I have various elements created in the response. One of these elements has a child element that should display another dynamically generated child element when hovered over. When testing this functionality using jQuery's .ho ...

Connecting an Objective-C object with RoboVM in Java

Hi there! I'm in desperate need of microphone access for my IOS app that I'm developing using libGDX and RoboVM. I came across information suggesting that I can connect an objC Class to a Java class. I tried to understand the documentation availa ...

Enhance your application with Java service wrapper and customize it further with additional command line

I'm currently utilizing Java Service Wrapper to encapsulate a Java application that I have created. I am in need of a way to pass extra command line arguments to my application through Java Service Wrapper. Let's say my application is named "mya ...

Updating values of nested objects by ID using Mongoose

As a newcomer to MongoDB, I've been struggling with a simple task that involves changing the status of a process. I've attempted using methods like "FindAndUpdate," "UpdateOne," and "FindByIdAndUpdate," but none seem to be working as expected. ...

Exploring the power of media query breakpoints within Chakra UI's global styles

Trying to incorporate a media query breakpoint in Chakra UI global styles has presented some challenges. An attempt was made using template literals for property names, but it was discovered that this approach is not supported: import { ChakraProvider, e ...

ngFor returning undefined despite array containing value

While iterating through an array using ngFor, I'm encountering an issue where trying to access data in the 'value' variable results in it being undefined. Why is this happening? myArray = ['a', 'b', 'c', 'd ...