Refresh the text area with the latest information received from the servlet using JavaScript

I am currently working on a program that involves calling a JavaScript function with multiple requests to a servlet. My goal is to execute these requests one by one and receive a response after each execution. However, the function I have only displays the result after all requests have been completed.

function cmd(args) {
    width = 0;
    var res = args.split('\n');
    var largo = res.length;
    var progressLength = 100 / largo;
    for (var i = 0; i < largo; i++)
    {
        if (res[i] == 'desconectar')
        {
            desconectar();
            break;
        }
        else
        {
            executeCMD(res[i]);

        }
    }
}
function executeCMD(args)
{
    $.ajax({
        type: "POST",
        url: 'Controlador',
        data: {cmd: args, operacion: 1},
        success: function (response) {
            document.getElementById('respuesta').value = document.getElementById('respuesta').value + response;
        },
        dataType: 'text',
        async: false
    });
}

If I include window.alert(response); within the success function, I am able to see the progress step by step and everything works smoothly. However, this triggers alerts that I would prefer not to have.

My end goal is to achieve something similar to what is shown in this image https://i.sstatic.net/MtaMI.jpg, but currently I am only able to display the last image.

Answer №1

If you're interested, the solution involved using a recursive function like the one below:

function cmd(args) {
width = 0;
move(0);
var res = args.split('\n');
var largo = res.length;
var valInit = 0;
if (largo > valInit)
{
    executeCMD(res, valInit);
}
}


function executeCMD(args, i)
{
     $(document).ready(function () {
            $.ajax({
                type: "POST",
                url: 'ControladorServlet',
                data: {cmd: args[i], operacion: 1, ticket: ticket, iddispositivo: sesion},
                success: function (response) {
                    var textarea = document.getElementById('respuesta');
                    var res = response.trim().split('\n');
                    if(error){//dc}
                    else
                    {
                        document.getElementById('respuesta').value = document.getElementById('respuesta').value + response.trim() + "\n\n";
                        var valor = (100) * (i + 1) / args.length;
                        move(valor);
                        if (i + 1 < args.length)
                        {
                            executeCMD(args, i + 1);
                        }
                    }
                },
                dataType: 'text'
            });
        });
    }

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

Tips for eliminating default classes from Mui Typography styling

I’ve been working on creating a Typography element and noticed some default MUI CSS classes added when debugging in the browser. I attempted to disable them by using empty arrays at the end of the sx prop, but it did not work as expected. In the image p ...

Program that duplicates text to clipboard upon clicking on the text

Hey there, I have a query regarding the script provided below: function copyElementText(id) { var text = document.getElementById(id).innerText; var elem = document.createElement("textarea"); document.body.appendChild(elem); ...

Discovering the method to extract a specific section from a lengthy string

Looking to extract phone numbers from an HTML source code using PHP? Each phone number in the code starts with 'phone=' and ends with %. For example, consider the following sample HTML code: b2e1d163b0b4dc6ebfa5&amp;t=s&amp;phone=9535503 ...

Generating a chart using solely the existing data components (values)

I have the following arrays: const elements = ['12345', '12346', '12347', '12348', '12349', '12350']; const fruits = ['Apple', 'Ball']; I want to create a Map using array ele ...

Discover the process of selecting an item from a list and viewing it on a separate page with the help of AngularJS and Ionic technology

I am struggling with creating a list of items that, when clicked, should take me to the corresponding post. Despite trying to use ng-click in the header, I suspect there is an issue with the route not functioning properly. As part of my testing process, I ...

Refresh the data list displayed within a specified div container

On my jsp page, I initially populate a model attribute with some data. Then, I use the following code to display this list on the jsp page: <c:forEach var="pattern" items="${patterns}"> <li class="list-group-item liitem"><st ...

Vue.js does not apply the "selected" attribute to set the HTML <option> tag to default

Trying to designate a default <option> tag from the available options. Utilizing v-model on the <select> tag, the vue.js documentation indicates the following approach: v-model will disregard the ... selected attributes present on form ele ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

Display a modal across all pages by incorporating a button component, regardless of its placement

I've implemented a header in my react app with a show dialog button that appears on all necessary pages. Currently, my approach to displaying the dialog is as follows: When the user clicks the button, I dispatch an action to the redux store { type:S ...

What is the maximum string length allowed for the parameter accepted by JavaScript's JSON.Parse() function?

Is there a maximum string length limit for the parameter accepted by JavaScript's JSON.Parse()? If I were to pass a string that surpasses this expected length, will it result in an exception being thrown or prevent the function from returning a valid ...

What sets apart a React component from a function-as-component in React?

React is really confusing to me right now. Take this simple react component for example: export default function Foo(){ return( <div> <div>some text</div> </div> ) } I want to add a child compone ...

Making an Ajax request with JSON is yielding unexpected variables that cannot be modified or removed

Attempting to make an AJAX call using a script: $.ajax({ url: pageURL, data: loadData, type: 'POST', cache: false, dataType: 'json', success: function (data) { //if the call was successful console.log(su ...

What are the steps to ensure that data retrieved from an API is accurately displayed in a table?

My current goal is to collect data from the crypto compare API and display it in a table format. Although I am able to generate the necessary elements and append them to the table body, I am facing an unusual issue. Each time I use a for loop to iterate th ...

Refresh the DATATABLE inside an AJAX call without reloading the entire page

I'm currently working with a table that utilizes the Datatable plugin. I have successfully implemented filtering and deletion functionality within the table. However, after deleting certain entries, I noticed an issue where the deleted item still app ...

Fill the drop-down menu with the present day's date, month, and year

I'm new to this, so please bear with me. I have some html and jQuery code: $(document).ready(function() { var d = new Date(); var month = d.getMonth() + 1; var year = d.getFullYear(); $("#month").val(month); $("#year").val(year) ...

Utilizing Bootstrap Modal functionality in a Django web application to enhance user experience

I am currently facing a minor issue in my Django application. I am attempting to utilize a modal from Bootstrap 4 along with AJAX to create a new object. Below you can view the code I used. However, when the user clicks the button, instead of seeing the mo ...

"Troubleshooting HTTP requests in Angular: Dealing with

I encountered an issue while attempting to test an http request with a dynamic URL. Within my service file, I have the following snippet: Snippet from My Service File: //other service codes.. //other service codes.. var id = $cookies.id; return $http.ge ...

Missing transitive dependencies have been identified within the node_modules directory when using npm

In my software development journey, I am working on two npm projects - one called X and the other called Y. Let's say that X relies on angular and has it specified as a dependency in its package.json file. To establish a connection between X and Y, I ...

Set up local npm packages for easy access by different projects

Can someone explain to me how npm works compared to Maven (I have a background in Java) when it comes to package management? I've developed a generic component using Angular 4 that will be used across multiple projects. I've published it to our n ...

Generating parameters on the fly from an array using jQuery

After implementing a successful plugin on my website, I am now looking to enhance it further by defining state-specific styles dynamically. The current setup allows for passing parameters for specific states, as shown below: $('#map').usmap({ ...