What methods can I use to gauge the loading time of an AJAX request and showcase a loading panel?

I am facing an issue with my AJAX request that sometimes deals with a large JSON object. I need to display a loading panel during this process, similar to the one shown in the image below (scaled at 45%):

https://i.stack.imgur.com/rw9ft.jpg

The problem I am encountering is the inability to predict the processing time of the JSON object on the server once it is sent via AJAX.

Below is the code snippet for my AJAX request:

$.ajax({
    url: './home/sumbit_json',
    type: 'POST',
    data: { 
      json_data: json_data, 
      user: user,
      entry: entry
    },
    dataType: 'json',
    success: function(data) {
      if (data.status == false) {
        alert("transaction failed");
      } else {
        alert("transaction successful");
      }

    }, // End of success function of ajax form
    error: function(xhr, status, errorThrown) {
      console.log("Error: " + errorThrown);
      console.log("Status: " + status);
      console.dir(xhr);
    },
});

Answer №1

$.ajax({
    url: './home/sumbit_json',
    type: 'POST',
                // this code will be executed before sending the request to the server
    beforeSend: function(){
        // set a variable outside of the ajax request to track time
        start_time = new Date();
    },
    data: { 
        json_data: json_data, 
        user: user,
        entry: entry
    },
    dataType: 'json',
    success: function(data) {
    if (data.status == false) {
        alert("transaction failed");
    } else {
        alert("transaction successful");
        //calculate how long it took
        alert(new Date() - start_time);
    }

    }, // End of success function of ajax form
    error: function(xhr, status, errorThrown) {
        console.log("Error: " + errorThrown);
        console.log("Status: " + status);
       console.dir(xhr);
    },
});

Consider sending the time taken data to the server and store it in a database. Utilize this information to calculate an average processing time. Adjust the progress bar to complete based on the stored average value before making a request. Additionally, speed up the progress bar if the request completes faster than expected.

Enhance this approach by conducting multiple tests with various throttling settings, like those available in Chrome. Evaluate the average values for different speed ranges and update the database accordingly.

Workflow summary: 1. Record request duration at internet speed X. 2. Store the time in the database. 3. Repeat steps 1-2 with varied speeds to establish averages. 4. Retrieve the average execution time from the database for the current speed/latency. 5. Set progress bar completion time based on the average found in step 4. 6. Update the average in the database after each request to refine accuracy.

By following this process, you can continually improve accuracy over time. Best of luck!

Answer №2

The technology you seek is known as a time-travel device, but unfortunately, it is still just a concept.

In the meantime, here's a workaround:

  1. Experiment with Developer tools to profile a typical use case. Repeat this process multiple times and gather the data. Take the average or select the longest non-outlier for a rough estimation.

  2. Set the progress animation to reach 90% within your estimated timeframe.

  3. When the request finally completes, animate it to 100% in the success callback function.

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

Is there a way to adjust the text color of a label for a disabled input HTML element?

If the custom-switch is active: the label text color will be green. If the custom-switch is inactive: the label text color will be red. A JavaScript (JQuery) method call can be used to activate one button while deactivating another. The Issue It appe ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

How can I send data in JSON format to a JavaScript AJAX request?

I've created a method that looks like this: public String getUTResult() throws IOException { BuildResultParser bp = new BuildResultParser(); BuildResultBean b = bp.getreadFile("C:\\bc.txt"); String str = b.getuTresult(); ...

Is there a way to grab code from a different HTML page using JavaScript and jQuery when the user clicks on something?

After testing various codes for the intended purpose mentioned in the title, I have observed a peculiar behavior. The code from settings.html appears briefly and then disappears rapidly. Javascript: function load() { $("#paste").load("settings.html") ...

The HTML head JavaScript files are not applicable to dynamic Bootstrap modals

I have broken down my PHP files into smaller parts, for example, tillbody.php contains everything from the HTML tag to the body tag, followed by navbar.php and so on. I am including these files in index.php. Here is the code for a better understanding: &l ...

Conceal elements with a single click of a button

How can I use jQuery to hide all li elements with an aria-label containing the word COMPANY when the Search from documents button is clicked? Here is the HTML code: <ul class="ui-autocomplete ui-front ui-menu ui-widget ui-widget-content" id="ui-id-1" t ...

Looking for assistance with creating a .NET regular expression specifically for parsing JSON data?

Currently, I am in the process of building a JSON parser for .NET that is effectively parsing JSON objects. However, I have hit a roadblock when it comes to parsing complex strings. For instance: The parser is able to successfully parse \"Hi there!&b ...

Unable to obtain the accurate response from a jQuery Ajax request

I'm trying to retrieve a JSON object with a list of picture filenames, but there seems to be an issue. When I use alert(getPicsInFolder("testfolder"));, it returns "error" instead of the expected data. function getPicsInFolder(folder) { return_data ...

Using the "if else" statement in a jQuery AJAX response

I have an Ajax function that is functioning correctly, but I want to display a different message when the Ajax response is: <h3>No Couriers found near you. Please select another location.</h3> If I receive this specific response, I want to sh ...

Connection error between frontend and backend was encountered

Whenever I try to register on my page and connect it to the database, I encounter an error after pressing the sign-in button... "Uncaught (in promise) TypeError: Converting circular structure to JSON --> starting at object with constructor &apo ...

Leveraging the power of VB.net to extract data from JSON code

Hello, I need to extract the values of 21, black jack, and tongits including their scores from the following JSON code: { "id": 1, "status": "PARTIAL", "scores": [ { "scoreCard": { "21": 0, "black jack": 0 ...

Uploading information from a confirmation page to the controller

Within this cshtml file, I have included a model. This specific page serves as a confirmation page where the user is able to review and verify that all entered information is correct before proceeding. There is a link button (not part of the displayed cod ...

Ways to execute a function when a button is clicked with a shared variable?

When creating buttons in HTML to control video speed, I encountered a strange issue. After successfully implementing the buttons for one video, they only worked on a second video and had no impact on the first one. Deleting the second video seemed to resol ...

Encountered an Internal Server Error while invoking PHP script through ajax request

When I click on a specific button on the screen, my goal is to trigger an AJAX call to execute a PHP script. This script will then fetch data from an object that contains information retrieved from a MySQL database and display it in a table. Each of the in ...

Modify the :after property of an element using jQuery

Is there a different approach I can take to achieve this desired outcome? Currently, the code snippet below is not yielding the expected results. $('.child_flyout:after').css({'top':'20px'}); Are there any alternative method ...

Updating MongoDB every 30 seconds using remote JSON data: A step-by-step guide

I'm currently working on parsing remote JSON data and storing it in MongoDB. The JSON data I am dealing with is dynamic, so I want to continuously update MongoDB with this dynamic data every 30 seconds. Here's an example of how I parse the JSON ...

Optimizing image dimensions on Instagram using JQuery

Question about using JQuery Instagram by Giovanni Cappellotto (https://github.com/potomak/jquery-instagram) I'm curious to know if there is a way to retrieve larger images from Instagram instead of just the standard 150x150px ones? I attempted to us ...

Reviewing the architecture that brings together Cappuccino, Django, and AJAX - let's make it perfect!

Trying to navigate the world of Cappuccino here. Looking for feedback from colleagues at StackOverview on the structure outlined below - the goal being to leverage the unique advantages of Django and Cappuccino without duplicating efforts... When a ' ...

Conceal the <div> element if the <span>

Is there a way to hide the content within this div if the prop-value is empty? I specifically want to hide the text "First class" when Prop-value does not have any value. Any solutions? <div> <span class='prop-name'>F ...

How can I prevent Sundays from being selected in a jQuery datetimepicker?

I'm currently working with a jquery datetimepicker and my goal is to exclude Sundays from the selection. How can I achieve this? Below is the jquery code that I am using: $(".datetimepicker").datetimepicker({ format: 'm-d-Y H:i', defaultD ...