Challenge encountered with implementing show/hide functionality using jQuery

$('#estimate').show(); is currently triggered after the API call is completed, but I am looking to make it happen before the API call.

The styling is applied only after the API call is finished. Is there an alternative method to achieve this?

If the response takes 3 seconds, the div is displayed after 3 seconds, but I want it to show before that time.

var formData = {
  "latlon1": "80.2707,13.0827",
  "latlon2": "78.7047,10.7905"
}
 $("#dSedan,#dSuv,#dInnova,#dSuvR,#dSedanR").on('click', function ()  {           $('#estimate').show();
  $("#estdistancedt").empty()
  $(".estdtbreakup").html("")
  $("#estimate .estamount").html("<img src='images/loading.gif' />");
                getEstimate(formData);
        })

function getEstimate(formData) {
 
  if (formData.latlon1 && formData.latlon2) {
    console.log(formData);

    var settings = {
      "url": serverurl + "rest/estimatecalculate",
      "method": "POST",
      "timeout": 0,
      'dataType': "json",
      "crossDomain": true,
      "headers": {
        "Content-Type": "application/json",
        "Access-Control-Allow-Origin": "*",
      },
      "data": JSON.stringify(formData),
    };
    $.ajax(settings).done(function(element) {
      $("#estdistancedt").empty().append("Distance:" + element.distance.toFixed() + " kms");
      $(".estamount").html(element.estimate);
      $(".estdtbreakup").html("[Base charges: &#8377; " + element.basecharge + " / Driver bata: &#8377; " + element.driverbata);
      if (element.isp != 0) {
        $(".estdtbreakup").append(" / ISP: &#8377; " + element.isp);
      }
      if (element.hillcharges != 0) {
        $(".estdtbreakup").append(" / Hill charges: &#8377; " + element.hillcharges);
      }
      $(".estdtbreakup").append(" + Toll at actuals]");
      $(".tripamount").val(element.estimate)
    });
  }
}

Answer №1

Kindly include a button and then proceed to execute your code in this manner

<button id="yourID">Submit</button>

var formdata = {
    "latlon1": "80.2707,13.0827",
    "latlon2": "78.7047,10.7905"
}

$(document).on('click', '#yourID', function(event) {
   $('#estimate').show(); // Display YOUR DIV ON BUTTON CLICK 
   $('.spiner').show(); // ACTIVATE SPINNER IF NECESSARY
   getestimate(formdata);
});

Lastly, remove $('#estimate').show(); from the function

function getestimate(formdata){
        $("#estdistancedt").empty()
        $(".estdtbreakup").html("")
        $("#estimate .estamount").html("<img src='images/loading.gif' />");
    if(formdata.latlon1&&formdata.latlon2){
        
            var settings = {
                "url": serverurl+"rest/estimatecalculate",
                "method": "POST",
                "timeout": 0,
                'dataType': "json",
                "crossDomain": true,
                "headers": {
                    "Content-Type": "application/json",
                    "Access-Control-Allow-Origin": "*",
                },
                "data": JSON.stringify(formdata),
            };
            $.ajax(settings).done(function (element) {
                $("#estdistancedt").empty().append("Distance:" + element.distance.toFixed() + " kms");
                $(".estamount").html(element.estimate);
                $(".estdtbreakup").html("[Base charges: &#8377; " + element.basecharge + " / Driver bata: &#8377; " + element.driverbata);
                if (element.isp != 0) {
                    $(".estdtbreakup").append(" / ISP: &#8377; " + element.isp);
                }
                if (element.hillcharges != 0) {
                    $(".estdtbreakup").append(" / Hill charges: &#8377; " + element.hillcharges);
                }
                $(".estdtbreakup").append(" + Toll at actuals]");
                $(".tripamount").val(element.estimate)
            });
        }
    }

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 avoiding HTML <tags> in the document.write function

I am trying to paint the actual HTML code within a tag using JavaScript but escaping it doesn't seem to be working. function displayHTMLString(n){ document.write("'<table>'"); for (i in range(0,n)){ ...

"Although there are no errors, the ng-switch directive within the ng-repeat is not functioning as

I'm working on setting up a simple image gallery where I can dynamically change the displayed image by setting a specific number for currentImage. Check out my HTML code: <div class="main_image" ng-switch on="current_image"> <img ng-rep ...

Uploading files using jQuery and AJAX

<div class="form-group"> <label class="form-control-label"> {{ __('Not Dosyası') }} : <span class="m--font-danger">*</span> </label> <br /> ...

Angular2+: Changing visibility of elements across multiple divs

Currently, my setup includes multiple divs containing toggling <i> elements. However, the issue I am facing is that when I click on one div's <i> (specifically the fa-bookmark), it triggers the toggling of all other corresponding <i> ...

Utilizing Ajax to display information

Being a novice in web development, I am working on a database that has a table named customers with columns for customer name and address. On the interface, there is a search field for customers along with another field for customer addresses. My goal is ...

Error encountered: DataTable - Unable to retrieve the 'length' property of a null value

I am currently using a datatable in my project: function drawRadnici() { $('#tableradnici').dataTable({ "ajax": { "url": 'track_radnici.php', "type": 'POST' ...

Calculating the total value of individual sections using Jquery

I have multiple sections, each containing three input fields: <div class="product_quantity"> <div class="color-quantity"> <input onkeydown="return myFunction(event);" name="custom_small" class="custom_small" type="text"> ...

My socket io connection is not working. There seems to be an issue with the connection io

After initiating my server, I am able to see the console.log message showing that the server is running on the specified port. However, I am not receiving the console.log message indicating a successful socket io connection with a unique socket id. import ...

How can I ensure that the first static tab in the second menu is always selected based on the user's selection from the first tab?

I have two tabs menus, the first one is created dynamically and the second one has a static first tab with other tabs created dynamically using ng repeat. My question is how to make the first static tab in the second menu selected no matter what the user s ...

Expand the div to fit 100% width inside the Blueprint container

I am currently working on a website and considering using the Blueprint CSS framework. You can view the site I'm referencing here: http://jsfiddle.net/timkl/uaSe3/ The Blueprint framework allows for a nice 24 column grid layout. One challenge I&apos ...

Is there a way to integrate a JQuery plugin into another plugin seamlessly without causing any conflicts or disruptions?

With the code provided, a flip effect is being generated using the JQuery Flip plugin. Within the "verso" property, there is a select menu with the ID #ddlBookletType, which triggers another JQuery plugin that creates dropdown menus. The current HTML stru ...

Unable to save the ID of an element into a jQuery variable

I am currently working on a project that involves an unordered list with anchor tags within it. I am trying to access the id of the li element that is being hovered over, but for some reason, the alert is returning undefined or nothing at all. Here is the ...

The attempt to bring in the model using `require` has resulted in an error. The `require` method used here, in combination with `path.join`, does

As a beginner in web development, I have been working on a project using MySQL, Node.js with Express. However, I am encountering a TypeError issue when using Sequelize. Can anyone kindly explain this to me and assist me in finding a solution? "seque ...

Excluding node modules when not included in tsconfig

Within my Angular project, there is a single tsconfig file that stands alone without extending any other tsconfigs or including any additional properties. Towards the end of the file, we have the following snippet: "angularCompilerOptions": { ...

JSON output for creating interactive charts using Highcharts

After much perseverance, I have successfully generated a chart. However, I am facing an issue where the data from JSON is not being displayed - resulting in a blank chart. The chart options currently look like this: series : [{ name: '2000' ...

Steps for layering three images with distinct red, green, and blue components using HTML and CSS

Is it possible to overlay three versions of an image, each with red, green, and blue components, in order to recreate the original image using only HTML and CSS? I have tried this HTML setup: <div id="container"> <img class="color" id="red" ...

Mongoose opts for the __v field over a traditional date field

My current model setup is causing unexpected behavior: const mongoose = require("mongoose"); const Schema = mongoose.Schema; const NewModelSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: "users", }, date: ...

What is the process of connecting a Yarn module to a Docker container in another repository?

I'm currently facing a challenge in linking a module to a Docker container from another repository. To provide some background, I have a container hosting a React application named launch-control-admin. This project relies on a yarn module called @com ...

Encountering an 'undefined' response when passing an array in Express's res.render method

After my initial attempt at creating a basic node app, I discovered that the scraper module was working correctly as data was successfully printed in the command window. Additionally, by setting eventsArray in index.js, I confirmed that Express and Jade te ...

Click on the print icon in the modal window

I have been working on a receipt generator for a client. The client can add payment receipts using the "Add" button, and upon submission, they have the option to convert it to PDF or print it. However, there seems to be an issue with printing as the text f ...