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

Issue: "Access-Control-Allow-Origin does not allow origin null" error message is returned when attempting to access a PHP file using jQuery's ajax method with dataType text/html selected

Why am I encountering this issue in Chrome when using dataType text and HTML? It seems to work fine if I output JavaScript and set the dataType to script. How can I return non-JavaScript data from a PHP file? Client-side code: $.ajax({ url: ...

Setting model value in Angular 2 and 4 from loop index

Is it possible to assign a model value from the current loop index? I've tried, but it doesn't seem to be working. Any suggestions on how to achieve this? Check out this link for my code <p *ngFor="let person of peoples; let i = index;"& ...

Ways to incorporate ng-app into an HTML element when HTML access is limited

In my current project, I am using Angular.js within a template system. The challenge I am facing is that I need to add ng-app to the html element, but I do not have direct access to do this on the page itself. Initially, my page structure looks like this: ...

When clicked, the onClick feature will reduce the number each time instead of initiating the timer

Currently, I am working on a meditation application using React. As a starting point, I implemented a 25-minute countdown feature. The challenge I am facing is that the timer starts counting down each time the button is clicked, rather than triggering it ...

Ways to change attributes of deeply embedded objects?

Imagine having a complex object with nested properties like this: const obj = { Visualization: { Lower: [{ name: "Part", selectedValue: "60-000" }], Upper: [{ name: "Part", selectedValue: "60-000" }], ...

Employing global variables in JavaScript files with Vue3

In my Vue3 project, I have defined global variables like this: app.config.globalproperties.$locale = locale A composable function has been created to dynamically retrieve these global variables: import { getCurrentInstance ) from 'vue' export f ...

The 'canvas' module could not be located in the system.Here are the required stacks:- /var/task/index.js- /var/runtime/index.mjs

I am currently developing a lambda function using the serverless framework. The function utilizes chartjs-node-canvas to create graphics, and everything runs smoothly on my MacBook when tested locally. However, when I deploy the function to AWS either dire ...

Is there a way to bring in a variable from the front end script?

Is it possible to transfer an array of data from one HTML file to another? If so, how can this be done? Consider the following scenario: First HTML file <script> let tmp = <%- result %>; let a = '' for (const i in tmp){ ...

What is preventing the Image Handler from being triggered by an AJAX client?

Below is the code snippet provided: Public Class Default4 Inherits System.Web.UI.Page Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim image1 As Image = Default4.GetSQLTable OtherBit ...

Error: Vue is unable to access the property '_modulesNamespaceMap' because it is undefined

I've been working on a simple web app to enhance my testing skills in Vue using Vue Test Utils and Jest. However, I encountered an error related to Vue while trying to console log and check if AddDialog is present in my Home file. The error message I ...

Adaptive Container with Images that are not stretched to full width

Is there a way to achieve the same effect as seen in images 2 and 3 here: Although these images already have their own "padding," I'm curious if it can be replicated using just jQuery and CSS? I would appreciate any help or insights on this. Thank y ...

encountering a type mismatch error while trying to retrieve data from an array

While attempting to retrieve data from a nested array, I encountered the error "TypeError: Cannot read property 'value' of undefined". It seems like I might be calling back incorrectly as I am receiving both the output and the error message in th ...

What is the best way to distinguish between inline javascript and dynamically created content in Express/Node.js?

I've encountered a bit of a noob-question despite having a few years of experience in web development. Despite searching Programmer Stack Exchange and Google, I haven't found an answer, so here goes. Currently, I'm working with the Express ...

When working with AngularJS, you can enhance your application by implementing a global AJAX error handler if one has

Is there a way to set a global AJAX handler that will only be called if an error handler is not already defined for a specific AJAX call? Some of my AJAX calls need to execute certain logic if an error occurs (such as re-enabling a button), while others s ...

What causes the child component to re-render when only the prop is changed and useCallback is used?

Child component will only re-render if its prop (numberModifier) is changed. The numberModifier uses useCallback with no dependencies, so it remains constant. To test this, I alter the value of "online" in the Application component which is a prop of Pare ...

Failure to inherit props in child components when using React-Redux

I've been following a React-Redux tutorial and encountered an error in the first part of the section titled "React Redux tutorial: asynchronous actions in Redux, the naive way". Post.componentDidMount src/js/components/Posts.js:12 9 | ...

I encounter obstacles when trying to execute various tasks through npm, such as downloading packages

Currently, I am facing an issue while trying to set up backend development using node.js on my personal computer. The problem lies with the npm command as it is not functioning correctly. Despite successfully installing a file without any errors, I am unab ...

Struggling to convert a JSON file into a TableView within a JavaScript application developed with Appcelerator

Trying to display a JSON file in a table using JavaScript and Appcelerator is proving to be quite a challenge. The output appears as an empty table when compiled to an example page. As someone relatively new to JavaScript and JSON, I'm seeking guidanc ...

How can I implement a pause in my JavaScript code?

Below is a snippet of code that I am using in my project: $.ajax({ url: $form.attr('action'), dataType: 'json', type: 'POST', data: $form.serializeArray(), success: function (json, textStatus, XMLHttpRequest) { ...

Exploring the properties of individual Vue components on a single page with v-for loop

Struggling to render a Vue component in a Rails app by iterating through an array of data fetched via Ajax. The Slim template (index.html.slim) for the index page includes a custom_form_item component, where items represent custom forms data from Rails and ...