Update the content of a div twice simultaneously

My AJAX call is currently working fine, but the response time is slow. To prevent users from clicking multiple times while waiting for a response, I want to display a message like "Converting please wait" before the data is received. Below is the code that I have implemented:

function postajax()
{
    document.getElementById('linksarea').innerHTML = "<img src='images/waiting.gif'> Converting please wait...";

    var xmlhttp;

    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
            document.getElementById("links").innerHTML=xmlhttp.responseText;
    }

    var links = window.document.getElementById('linksarea').value;

    xmlhttp.open("POST","ajax.php",true);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.send("links="+links+"&username=xxxx");
}

This is the HTML section where I am making the modifications:

<div id="memberright">
  Convert the links here<br />
  <textarea name="links" id="linksarea" cols="65" rows="10"></textarea><br />
  <input type="button" id="buttonr" onclick="postajax()" value="Convert">
</div>

<div id="ajax">
  <div id="links">
  </div>
</div>

Answer №1

Your current usage is as follows:

document.getElementById('linksarea').innerHTML = "<img src='images/waiting.gif'>
   Converting please wait..."; 

This code snippet sets the innerHTML to display a loading image along with a message indicating that conversion is in progress. Later on, you attempt to retrieve the value of the element using:

window.document.getElementById('linksarea').value;

The value attribute is typically found in an input element and not within innerHTML. Therefore, this approach may encounter issues.

If you are looking to modify a div element identified by #links, consider using the following code snippet based on your question's context:

document.getElementById("links").innerHTML = "<img src='images/waiting.gif'>
       Converting please wait..."; 

// Alternatively, if there is another div with ID 'linksarea'

document.getElementById("linksarea").innerHTML = "<img src='images/waiting.gif'>
       Converting please wait..."; 

It seems like the root cause could be targeting the wrong element for modification without observing your HTML structure. Ensure the correct element is being modified to address this issue effectively.

Update:

If you prefer using jQuery library, simplify AJAX requests by adopting the following approach:

function postajax(){
    $('#links').html("<img src='images/waiting.gif'> Converting please wait...");

    var params = "links=" + $('#linksarea').val() + "&username=xxxx";

    $.ajax({
        url: "ajax.php",
        type: "POST",
        data: params,
        success: function(result){
            $('#links').html(result)
        }
    }); 
}

jQuery streamlines AJAX operations through functions like $.ajax(). It is advisable to grasp the underlying mechanisms before leveraging libraries to maximize comprehension and promote positive coding practices.

Answer №2

To enhance the functionality of the onreadystatechange function, consider including an additional if statement. The state value that corresponds to "loading" is '1'. You can refer to this resource for guidance: example website. Your code should resemble the following:

  xmlhttp.onreadystatechange=function()
  {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
          document.getElementById("links").innerHTML=xmlhttp.responseText;
      }
      else if (xmlhttp.readyState==1 && xmlhttp.status==200)
      {
        document.getElementById('linksarea').innerHTML = "<img src='images/waiting.gif'> Converting please wait...";
      }
  }

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

Issue with module exports not being defined in IE11/Edge

I am experiencing difficulties with an npm module that was updated to ES2015. My application is built in ES2015, bundled by browserify, and compiled with babelify. I am currently trying to upgrade a npm module called credit-card for validation, which has ...

Difficulty encountered when trying to use Bootstrap tooltip with Bootstrap icon

Attempting to implement bootstrap tooltips on bootstrap icons with the following code: <body> <script> const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]') ...

I require assistance in clearing the text field under specific circumstances

Incorporated in my webpage are text area controls that have been coded to automatically create a bullet-list when the user clicks on the text area or presses the 'ENTER' key. However, there is an issue - if the user clicks on the text area withou ...

React Intersection Observer Triggering Memory Leaks

Issue Description: I encountered a problem with my React app crashing on mobile. The Chrome dev tools revealed that garbage collection wasn't triggering, and upon inspecting the heap, I found that the top constructors by retained size were all linked ...

Error: Unable to locate module 'child_process' in the context of NextJS + Nightmare

Encountering an issue while trying to compile a basic example using Next JS + Nightmare Scraper. Upon attempting to access the page, I am faced with the following error message, and the page fails to load. PS C:\Users\lucas\Documents\Pr ...

Issue with publishing npm package using yarn package manager

I'm currently in the process of releasing a fresh package. Utilizing ES6, I've been transpiling my files through babel to start with. However, I've hit a roadblock at this particular stage: https://i.stack.imgur.com/iIVp6.png This part se ...

When the form is submitted, the text input vanishes and then the page is refreshed using AJAX technology

Can anyone help me troubleshoot why my page is reloading even though I used AJAX, and how to prevent it from clearing my input text after clicking the submit button? I tried using the show method to resolve this issue but it didn't work. <form met ...

Enhancing AJAX store in ExtJS with custom headers

Despite configuring the headers of my store, I keep encountering an error message like this: No 'Access-Control-Allow-Origin' header is present on the requested resource. Below is my proxy configuration for Ext.data.Store: proxy : { ...

Can REST calls be initiated when the CSP is unable to be modified from the default-src: 'none'?

Sometimes, I wonder if this question is silly because it goes against the purpose of the Content Security Policy. There's a webpage located at foo.baz.com that requires data from bar.baz.com to function locally. Below is the code snippet for the func ...

Reduce the use of javascript by incorporating NPM specifically after publishing instead of during the building process

My goal is to minify JS files using NPM commands, but I want the minify command to only run after Post Publish and not on Build. Unfortunately, it currently runs after both build and publish. In my Package.json file, I have the following code: "scripts" ...

When it comes to utilizing jQuery for the mobile view, how many jQuery libraries are recommended for optimal performance?

I'm currently constructing a website using ROR, and for the mobile view, I've implemented the mobile_fu gem. The designer provided me with a design for the mobile view that includes various jQuery sliders, players, image sliders, drop-down menus ...

"Trouble with Angular's http.get method failing to retrieve data from MySQL through Node

I am struggling to retrieve data from MySQL using Angular and Node.js. Despite trying, I am unable to make it work. When I check Postman using the link http://localhost:8080/locations, I can see the data. { "status": "200", "items": [ { "cit ...

Why does the value become "Undefined" once it is passed to the controller function?

I am unsure why the console.log function returns "undefined". $scope.onSizeSelected = function(productId, sizeQtyPrice){ console.log('The selected size is: ' + sizeQtyPrice); $scope.updateSelectedProductBySizeSelected(productId ,sizeQtyPrice ...

Dynamic value updates using jQuery input type formulas

I need help with a form that has two inputs: The first input allows the user to enter an amount, such as 1000. The second input is read-only and should display the value of the first input plus 1%. For example, if the user types in 1000 in the first fie ...

Determine distinct items in an array that match a predefined criteria

I have a list of objects with two keys, img1 and img2. I need to identify unique objects based on the values of img1, while also retaining the corresponding value of img2. This is the current code I am using: const imgs_arr = [ ...new Set( inpu ...

Getting a surprise image from the collection

I am experiencing an issue with retrieving images from an array. I have an array containing 6 variables that represent the paths to the images. However, when I use console.log at the end, it returns a random variable like sk11, sk15, etc., which do not c ...

What are the pros and cons of passing an imported object from a parent component to its children as props versus directly importing that object within the children components?

My current project involves a helper object known as TimeHelper, which is used for time-related tasks. This object is required in multiple components within the top-level parent component. I am contemplating whether it would be advantageous to import Time ...

Retrieve all references to child elements in React

I am working on a component that renders dynamic children, and I need to assign a unique ref to each child (e.g. ref={'childID' + index}) After the children have been loaded, I am looking for a way to loop through them and access their refs. Is ...

Is there a way to retrieve the content of an element using JavaScript?

I'm currently working on retrieving the value and content of an option element. I've managed to obtain the value using this.value as shown in the code snippet below: <select name='name' id='name' onchange='someFunctio ...

The best approach to incorporating interactive animation in next.js

My vision is to develop a character creation application using next js. The app should empower users to customize the character using sliders and gender selection buttons. The ultimate goal is to have a 2D animated version of the character that dynamicall ...