Removing the alert statement causes JS to cease functioning

I am encountering a common issue with my code while constructing a Treemap layout using d3.js. The code seems to only work when an alert statement is included in it. Let me briefly outline the structure of the code below,

default.HTML file and FetchData.java

  1. The default HTML file contains a form with 3 radio buttons and 2 text boxes (used for date filtering).
  2. There is a button that triggers the loadNewData() function upon clicking.
  3. The loadNewData() function makes an AJAX call to a servlet named "FetchData.java" with query parameters from the text boxes.
  4. The servlet, "FetchData.java", connects to the database on each click event, extracts data, and writes it to a file called "OutputJSON". A unique random number is generated for every click event.
  5. The filename is then sent back to the AJAX call as input to another JS function called wrapperFunc(str).
  6. This function utilizes d3.json by taking the file URL (json data file) and generates a treemap visualization.

Step 6 functions correctly when an alert statement precedes the call to wrapperFunc(str). If the alert is removed, the functionality fails.


    <!-- DEFAULT.HTML -->
    <!DOCTYPE html>
    <html>
        <head>
            <title></title>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <meta http-equiv="Pragma" content="no-cache">
            <meta http-equiv="Cache-Control" content="no-cache">
            <meta http-equiv="Expires" content="Sat, 01 Dec 2001 00:00:00 GMT">
            <script type="text/javaScript" src="d3/d3.js"></script>
            <script>
                [JavaScript code...]
            </script>
        </head>
        <body>
             [Form elements and JavaScript code...]
        </body>
    </html>

FetchData.java - is a servlet that retrieves the required data from the database and writes it to a file


    /*
     * Java Servlet code snippet 
     */

    import java.io.IOException;
    import java.io.PrintWriter;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import com.aol.poc.d3js.dbConnect.NetezzaJdbcConnection;
    import com.aol.poc.d3js.properties.*;
    import com.aol.poc.d3js.treemap.CsvToJson_V2;
    import java.text.SimpleDateFormat;
    import java.util.Date;

    @WebServlet(name = "FetchData", urlPatterns = {"/FetchData"})
    public class FetchData extends HttpServlet {

        @Override
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {

            String from="",to="",filetod3="";
            from = request.getParameter("from");
            to = request.getParameter("to");    

            response.setContentType("text/html");
            response.getWriter().write(generateJSONDataFile(from,to));
            response.getWriter().flush();
        }        

        public String generateJSONDataFile(String from,String to){
            NetezzaJdbcConnection njc = new NetezzaJdbcConnection();
            CsvToJson_V2 readCsv = new CsvToJson_V2();

            if(from == null || to == null){
                System.out.println("Inside if null");
               njc.extractData();
            }            
            else{
                System.out.println("Inside else");
                njc.extractData(from,to);
            }            
               String filetod3 = readCsv.readCsv();    

               return filetod3;
        }    
    }

Answer №1

After extensive troubleshooting, I have managed to identify the root cause of the issue I was encountering. It turns out that the d3.json(url,callback) function itself performs an AJAX call. When I passed the filename (JSON data) retrieved from the servlet to the d3.json function, it triggered another request to the server to fetch the file. Due to the asynchronous nature of this process, the d3 code would execute before the data was fully received. This issue became apparent when the console displayed an error message (object XMLHttpRequest) instead of the expected JSON object ([Object Object]).

To resolve this issue, I made the decision to eliminate the d3.json function entirely. Instead, I opted to pass a complete JSON string from the file and utilized the JavaScript eval() function to convert it into a JSON object. By doing so, I successfully executed the d3 code without encountering any alert-related problems. Below are the crucial segments of the revised code. Please note that the CSS code has been omitted for brevity, and the servlet code remains unchanged except for the modification where return filetod3; now returns the JSON data rather than just the JSON file name.

<html>
    <head>
        <!-- Header content goes here -->
    </head>
    <body onload="loadNewData()">
        <h3>Visualization Demo Using D3.js</h3>
         <!-- Form and other HTML elements go here -->
      
        <script>
            // JavaScript functions and logic go here
        </script>
    </body>
</html>

Answer №2

I found that incorporating jQuery Ajax with the option of asynchronous: false was very beneficial to me.

 function  initConfig() {
            console.log('initConfig:start');
            $.ajax({
                type: "POST",
                url: "router.php", 
                dataType: 'json',
                async: false,
                data: {"ajax_mode":"init-config"},
                success: function(msg){
                   window.storeobject = msg;
                   },
                error: function(){
                    alert("failure");
                }
            });
        }

Best regards, Andrzej Kmicic

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

Install Chakra UI in the latest Next.js project directory

Recently, I decided to incorporate Chakra UI v2.4.9 into my Next.js project running on version v13.1.6. To ensure a seamless integration, I followed the detailed instructions provided in Chakra UI's official guide for Next.js. However, I encountered s ...

Is there a potential danger in utilizing wp_update_post alongside AJAX to transmit extensive chunks of HTML content?

I am currently developing a front-end editor that utilizes AJAX to dynamically update the content on the page. It works by using JavaScript to extract sections of HTML components and then inserting them into the page content, enclosed in <!-- wp:html - ...

Generate a Flask template using data retrieved from an Ajax request

Struggling with a perplexing issue. I'm utilizing Ajax to send data from my Javascript to a Flask server route for processing, intending to then display the processed data in a new template. The transmission of data appears to be smooth from Javascrip ...

Dynamically add index to attribute as it updates

Having an issue with my dynamic button element: <button v-on:click="changeRecord(element)" v-b-modal.modal-5>Aendern</button> This button is generated dynamically within a v-for loop. Instead of manually including the attribute name like v-b- ...

The padding of elements changes accordingly as the dimensions (width/height) of the header are adjusted

Currently, I'm tackling the challenges of working on my website and trying to understand JavaScript better. I am facing an issue where I want my aside menu's padding to adjust when my header shrinks in height. Furthermore, at the end of the web ...

Tips for refreshing the table data following the deletion of a record within an AJAX success function

Here is the code I'm currently dealing with: While my overall code is functioning properly, I am encountering an issue with the success function of my Ajax. Specifically, I am trying to display the updated record after deleting a row without needing ...

Tips for troubleshooting and resolving the npm ERR! code E404 issue in Vue.js when implementing a datepicker

I am a newcomer to Vue.js and I am currently exploring the use of a datepicker from However, upon importing the script for usage, I encountered the following message: 'VMdDateRangePicker' is declared but its value is never read.ts(6133) Cou ...

Issue with Asp.Net MandatoryFieldValidator and JavaScript What You See Is What You Get Editor

Currently, I am utilizing the Javascript WYSIWYG tool from OpenWebWare along with Asp.Net's RequiredFieldValidator on a TextBox that is linked to the WYSIWYG. So far, everything is functioning properly, however, upon the first form submission attempt, ...

Iterating through each object in the JSON file to showcase details about planes

Question How do I set up a functional example of these airplanes? Background I seem to have the initial part working, indicating that my loop may be causing issues. While I can extract the number of planes, I'm facing difficulties displaying all th ...

Avoid the headache of accidentally submitting a form multiple times with the help of rails 4 remote: true

view = form_tag foo_path, method: :get, class: 'form-inline', role: 'form', remote: true do .form-group = select_tag :year, options_for_select(@years, Date.today.year), class: 'form-control', prompt: 'Year' ...

(Original) redirect from specific url / url detection New text: "Redirection

Sorry for the long and confusing question, my apologies for wasting your time. I am still learning programming and what I really wanted to ask is "how can I retrieve a GET parameter using JavaScript?" Apologies for any inconvenience. ...

The embed code is failing to load the HTML in the correct location

We're experiencing an issue with embedding a 3rd party form (HubSpot Form) on our website. Sometimes, the HTML of the form isn't located in the correct position - it should be placed directly after the script. <script>hbspt.forms.create({ ...

Unable to display image on HTML page transmitted via socket in Java

After successfully loading my simple HTML in Chrome and seeing it display correctly, I encountered a troubling issue when trying to pass it through a Java socket. Despite only passing bytes through the socket, the image always appears broken. The perplexin ...

Printing a docx file from Node.js to a physical printer

I'm currently working on a project in node.js where I need to enable users to print a docx file directly from the printer. Is there anyone out there who can guide me on how to achieve this using Node.js? ...

A Java database system stored entirely in memory, with the capability to be saved as one large block of memory

I am seeking an in-memory relational (SQL) database compatible with Java that allows me to serialize the entire state, similar to HSQLDB. wholeDatabase.serialize(outputStream); newCopyOftheDatabase.loadFrom(inputStream); Alternatively, the database could ...

Basic Block - Three.JS

My goal was to create a simple rotating 3D cube using the Three.js library for WebGL. Despite following numerous tutorials, I can't figure out why my code only displays a black screen with no geometry. //Setting window dimensions var width = windo ...

"Utilizing AngularJS to interact with external API endpoints without using

Can you explain why I am unable to access $scope.auditorium outside the $http method, while I can access other $http objects (e.g. $scope.exhibition) in another $http ($scope.auditorium)? Through concatenating both scopes at the end using $scope.combine C ...

Display header only once with AngularJS ng-repeat

I have two lists, namely the persons and animals, which I am displaying using ng-repeat. My goal is to present these two lists in a single table with a heading. Below is an example of how I envision presenting the data. I have attempted to achieve this usi ...

Guide to sending text in a web table cell with Selenium and Java

I am attempting to input a value of "100" into Position (row: 2, column 3) of a Table located at: The following code snippet is being used. Can you please identify what could be wrong with it? Code: driver.get("https://keisan.casio.com/exec/system/1380 ...

What sets apart 'Survival Count' from 'Tenuring Threshold' in G1 Garbage Collection?

After analyzing a garbage collection report, I noticed the intriguing presence of the Tenuring Summary section at the bottom, which includes a metric called Survival Count. This metric does not appear explicitly in the GC logs when using -XX:+PrintTenuring ...