Various successful functions in Ajax

I am currently using an Ajax script to fetch data from my database and insert it into multiple textboxes. Along with posting the data, I also need to perform calculations using these textboxes.

However, upon running the script, I noticed that all calculations are being executed simultaneously. Is there a way to incorporate multiple onSuccess functions in the script to ensure that the codes run in the correct sequence?

Below is the snippet of my current script:

$(document).on('change', '[id^=vat1]', function getVat12() { 
  console.log("getVat2 before ajax", jQuery('#vat1').val());
  jQuery.ajax({ 
    url: './get/get2.php', 
    method: 'POST', 
    data: {'id' : $('#vat1').val()},
    success: function(response){ 
      console.log("getPrice after ajax", jQuery('#vat1').val());
      jQuery('#percentage1').val(response);

      // code 1 
      var numVal1 = Number(document.getElementById('quantity1').value);
      var numVal2 = Number(document.getElementById('price_ex1').value);
      var totalValue1 = numVal1 * numVal2
      document.getElementById('totalprice1').value = totalValue1.toFixed(2);

      //code 2
      var numVal3 = Number(document.getElementById('totalprice1').value);   
      var totalValue2 = numVal3;
      document.getElementById('subtotal').value = totalValue2.toFixed(2);

      //code 3
      var numVal4 = Number(document.getElementById('totalprice1').value);
      var numVal5 = Number(document.getElementById('percentage1').value);
      var totalValue3 = numVal4 / 100 * numVal5
      document.getElementById('vat2').value = totalValue3.toFixed(2);
    }, 
    error: function (request, status, error) { 
      alert(request.responseText); 
    }, 
  });     
});

Answer №1

If promises are within your realm of expertise, the same outcome can be reached by following these steps.

$(document).on('change', '[id^=vat1]', function fetchVat12() { 
    // Utilize Ajax to retrieve the product price 
    console.log("Obtaining Vat2 before Ajax", jQuery('#vat1').val());
    jQuery.ajax({
        url: './get/get2.php',
        method: 'POST',
        data: {
            'id': $('#vat1').val()
        },
        success: function (response) {
            // Insert the price into the text field 
            console.log("Setting Price after Ajax", jQuery('#vat1').val());
            jQuery('#percentage1').val(response);
            calculateTotalPrice().then(function(res) {
                calculateSubTotal().then(function(res1) {
                    calculateFinalTotal().then(function(res2) {
                        console.log('All Set');
                    });
                });
            });
        },
        error: function (request, status, error) {
            alert(request.responseText);
        },
    });
  });

 function calculateTotalPrice() {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            var numVal1 = Number(document.getElementById('quantity1').value);
            var numVal2 = Number(document.getElementById('price_ex1').value);
            var totalValue1 = numVal1 * numVal2
            document.getElementById('totalprice1').value = totalValue1.toFixed(2);
            resolve('totalGenerated');
        }, 0)
    });
}

function calculateSubTotal() {
    return new Promise(function(resolve, reject) {
    setTimeout(function(){
        var numVal3 = Number(document.getElementById('totalprice1').value);
        var totalValue2 = numVal3;
        document.getElementById('subtotal').value = totalValue2.toFixed(2);
        resolve('subTotalGenerated');
    }, 0)
});
}

function calculateFinalTotal() {
return new Promise(function(resolve, reject) {
    setTimeout(function(){
        var numVal4 = Number(document.getElementById('totalprice1').value);
        var numVal5 = Number(document.getElementById('percentage1').value);
        var totalValue3 = numVal4 / 100 * numVal5
        document.getElementById('vat2').value = totalValue3.toFixed(2);
        resolve('finalAmountGenerated');
    }, 0)
});
}

Answer №2

Regarding your inquiry:

Is there a way to incorporate multiple onSuccess functions in my script so that the code executes in the correct sequence?

Indeed, it is possible to create multiple onSuccess functions as stated in the jQuery ajax documentation:

Starting from jQuery 1.5, the success setting can accept an array of functions, each of which will be executed sequentially.

Based on this information, you could utilize an array of callbacks for ordered execution. Below is an example of how you can implement this concept in your code:

$(document).on('change', '[id^=vat1]', function getVat12() { 
  console.log("getVat2 before ajax", jQuery('#vat1').val());
  jQuery.ajax({ 
    url: './get/get2.php', 
    method: 'POST', 
    data: {'id' : $('#vat1').val()},
    success: [code1, code2, code3], 
    error: function (request, status, error) { 
      alert(request.responseText); 
    }, 
  });     
});

function code1(response){ 
  console.log("getPrice after ajax", jQuery('#vat1').val());
  jQuery('#percentage1').val(response);

  // Code 1 
  var numVal1 = Number(document.getElementById('quantity1').value);
  var numVal2 = Number(document.getElementById('price_ex1').value);
  var totalValue1 = numVal1 * numVal2;
  document.getElementById('totalprice1').value = totalValue1.toFixed(2);
}

function code2(response){
  // Code 2
  var numVal3 = Number(document.getElementById('totalprice1').value);   
  var totalValue2 = numVal3;
  document.getElementById('subtotal').value = totalValue2.toFixed(2);
}

function code3(response){ 
  // Code 3
  var numVal3 = Number(document.getElementById('totalprice1').value);   
  var totalValue2 = numVal3;
  document.getElementById('subtotal').value = totalValue2.toFixed(2);
}

Addressing your concern:

Upon executing the script, I notice that all calculations happen simultaneously

This observation contrasts with what Quentin articulated. Since none of the functions are asynchronous, they should run in a sequential manner.

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

HeaderView in Angular Framework

When exploring the best practices for organizing an AngularJS structure, I came across the recommendation to implement partial views as directives. Following this advice, I created a directive for my app header. In my specific header design, I included a ...

Transform your CSS styles into Material-UI makestyles

I am looking to implement an IconButton with a website preview feature that appears when the user hovers over the help icon. I came across a similar solution using CSS, but I need to convert it to Material UI. Here is the CSS code that needs to be converte ...

Exploring the capabilities of Socket.IO in Node.js for establishing a connection with an external server

Background: My localhost (referred to as Server A) hosts a node.js server, while an external server running node.js can be found at (known as Server B). Although I lack control or access over Server B, which serves as a dashboard site for an IoT device in ...

Dragging objects on a map is done using jQuery and it causes them to bounce

Currently, I am working on implementing the JQuery Draggable feature. My idea is to create a map where I can attach image Divs to it dynamically using Jquery. So far, I have been successful in adding the Divs and making them draggable around the map effici ...

Transmitting Data via Socket.io: Post it or Fetch it!

I am struggling to send data via POST or GET in socket.io without receiving any data back. My goal is to send the data externally from the connection. Take a look at the code snippets below: Server-side code: app.js io.sockets.on('connection', ...

Component re-rendering and initializing useReducer

I made some revisions to this post. Initially, I shared the entire problem with my architecture and later updated it to focus directly on the issue at hand in order to make it easier for the community to provide assistance. You can now jump straight to the ...

"Error TS2339: The property specified does not exist within type definition", located on the input field

When a user clicks a specific button, I need an input field to be focused with its text value selected entirely to allow users to replace the entire value while typing. This is the markup for the input field: <input type="text" id="descriptionField" c ...

Unable to remove spaces in string using Jquery, except when they exist between words

My goal is to eliminate all white spaces from a string while keeping the spaces between words intact. I attempted the following method, but it did not yield the desired result. Input String = IF ( @F_28º@FC_89º = " @Very strongº " , 100 , IF ( @F_28 ...

I'm encountering a 400 error when using xsr.send within my AJAX request in a .NET Core application

I encountered an error 400 while attempting to make an Ajax call in .NET core 2.0 with entity framework using jQuery 2.2. This is how my Controller Method is structured: [HttpPost] [ValidateAntiForgeryToken] public JsonResult RetrieveDateCollectio ...

Retrieve the chosen date from the Ajax calendar extender control

Using the Ajax Calendar extender control in my asp.net 3.5 application has been quite helpful. I am wondering how I can retrieve the selected date from the Ajax calendar extender control in the code behind file. For instance, if I select 01/01/2011 from ...

Utilizing PNG images with color in CSS, HTML, or JavaScript

On my website, I have an image in PNG format. I am wondering if there is a way to change the color of the image using HTML5, JavaScript, or CSS. Ideally, I would like the image to be changed to white by inverting its colors (changing black to white, not al ...

What is the best way to sort through the data retrieved using jQuery.ajax()?

When utilizing the jQuery.ajax() method, I'm facing challenges in filtering the returned data to extract exactly what I need. Although it's straightforward with .load() and other jQuery AJAX methods, I specifically require using .ajax(). For ins ...

How can I personalize the color of a Material UI button?

Having trouble changing button colors in Material UI (v1). Is there a way to adjust the theme to mimic Bootstrap, allowing me to simply use "btn-danger" for red, "btn-success" for green...? I attempted using a custom className, but it's not function ...

I am unable to access the state after setting it in useEffect in React. Why is this happening?

After rendering the component, I utilize socket io to send a socket emit in order to fetch data within the useEffect hook. Subsequently, I also listen for the data that is returned. However, upon receiving the data back from the socket, I update the stat ...

The body onload function fails to run upon the page loading

I'm having trouble with my body onload function not executing. When I load the page, I want to display all records that are selected in the drop_1 dropdown and equal to ALL. I have a script that sends values q and p to getuser.php. The values sent are ...

React and Redux Toolkit collaborated to create a seamless shared state management system,

Currently, I am developing a simple application to experiment with Redux Toolkit alongside React. Despite being able to view the object in the Redux Chrome tab, I am facing difficulties accessing it using React hooks within components. The code for my sli ...

Is it possible to utilize Jquery in order to add an opening <tr> tag and a closing </tr> tag within a dynamic table?

I have been experimenting with the code snippet below in an attempt to dynamically add a closing tag followed by an opening tag after every three cells, essentially creating a new row. Progress has been made as the DOM inspector shows a TR node; h ...

Obtaining the current value with each keystroke

While working with vue.js, I'm building a table that contains an input field called quantity. However, when I start typing the first word, it shows 'empty' on the console. If I type 3, it displays empty; and if I type 44, it prints 4. I am ...

Utilizing the Global Module in NestJs: A Step-by-Step Guide

My current project is built using NestJS for the back-end. I recently discovered that in NestJS, we have the ability to create Global Modules. Here is an example of how my global module is structured: //Module import {Global, Module} from "@nestjs/commo ...

Utilize jQuery and Ajax for Efficient Record Insertion and Loading

I've been diving into the world of jQuery and Ajax, and stumbled upon an excellent tutorial for inserting and loading records. This helpful tutorial Despite successfully storing the comments in the database, I'm facing an issue where the insert ...