Ensure that each Javascript function call in MVC 4 waits for the previous one to complete before executing

I am trying to run two JavaScript functions, but the second function needs to wait for the first function to finish.

View:

<button id="DefinirEstab" class="btn btn-success btn-lg" data-toggle="modal" data-target="#myModal" onclick="saveContrato(); CountEstab()"> Define
 </button>

First JavaScript function:

function saveContrato() {
$("#formContrato").ajaxSubmit({
    type: "POST",
    url: $("#formContrato").attr("action"),
    clearForm: false,
    success: function () {
        $("#Serie").attr("disabled", true)
    }
});
$("#DefinirEstab").attr("onclick", "CountEstab()");

}

Second JavaScript function (waits for the first one to finish):

function CountEstab() {

    //Save data in the service table
    var Serie = $("#Serie").val();
    var NumDoc = $("#NumDoc").val();
    $.getJSON("/Contrato/saveCabecalhoServicos", {
        serie: Serie, numDoc: NumDoc, idForn: window.IdFornecedor, idFilial: e
    });

} else {
    alert("Missing mandatory data!!");
}

}

Answer №1

Utilize the second function as a callback for the initial function.

function submitForm(callback) {
    $("#contractForm").ajaxSubmit({
        type: "POST",
        url: $("#contractForm").attr("action"),
        clearForm: false,
        success: function () {
            $("#Series").attr("disabled", true)
            callback();
        }
    });
    $("#DefineEstablishment").attr("onclick", "CountEstablishments()");
}

submitForm(CountEstablishments)

Answer №2

Execute CountEstab() within the success function.

html

<button id="DefinirEstab" class="btn btn-success btn-lg" data-toggle="modal" data-target="#myModal"> Define
</button>

javascript

$('#DefinirEstab').on('click', function() { 
    saveContrato();
    return false;
});   

function saveContrato() {
    $("#formContrato").ajaxSubmit({
        type: "POST",
        url: $("#formContrato").attr("action"),
        clearForm: false,
        success: function () {
            $("#Serie").attr("disabled", true);
            CountEstab();
        }
    });
}

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

What is the best way to include optional parameters in a RESTful API?

I'm currently utilizing the REST API found at this link. Here is an example code snippet for reference: server = "https://rest.ensembl.org" ext = "/vep/human/hgvs/ENSP00000401091.1:p.Tyr124Cys?" r = requests.get(server+ext, header ...

Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem. In my data structure, I have arrays ...

Adjusting the value of a user form with multidata in PHP and Javascript

I am looking for guidance on how to modify the value of an input in a form that contains multiple data entries. Here is my form: <form method="post" action="pax-flight.php#pax-flight" class="paxform"> <input type="hidden" value="{"data":{"us ...

Angular not displaying input value correctly in first loop index

Hello, I am currently working on a rent calculator application using Angular. The app takes three inputs: total rent, annual rent increase amount, and the number of years to calculate for. One issue I am facing is that the for loop does not print the enter ...

React BrowserRouter causing issues with "invalid hook calls"

Just starting out with React and I am working on setting up paths using BrowserRouter, Route, and Routes in my code. import React from "react" import "./App.css"; import { BrowserRouter as Router, Route, Routes } from 'react-router ...

Encountered an error while trying to create a new NestJS project using yarn: Command execution failure - yarn install --

Having trouble installing a new NestJs project using yarn. Operating system : Microsoft Windows [version 10.0.19044.3086] Node version : 18.17.1 npm version : 9.6.7 yarn version : 1.22.19 Nest cli version : 10.1.16 I attempted to install by running : npm ...

Is there a way to prevent a button from being clicked until a certain callback function is triggered

I am struggling with configuring my contact form to disable a button when the form is not valid or a recaptcha is not selected. <form name="contactForm" data-ng-controller="ContactCtrl" novalidate> ... <input class="form-control" name="email" typ ...

If the condition is true, apply a class with ng-class when ng-click is triggered

I am facing a situation similar to toggling where I am adding the class col-xs-6 to divide the page into two views. Initially, when I click, I set a variable value as true and in ng-class, I check for a condition to append the col-xs-6 class. Below is the ...

A guide on utilizing nodejs to automatically open the default browser and direct it to a specific web address

I am currently developing a program using Node.js. One of the features I aim to implement is the ability to launch the default web browser and direct it to a particular URL. I want this functionality to be compatible across Windows, Mac, and Linux operat ...

Is there a way to gradually reveal an element as I scroll to a specific position?

If the window top position is about 100px from the bottom, I want to create a fading in/out effect for the element overlay. Check out this image Any ideas on how to achieve this? .section-card{ position: relative; height: 500px; line-heigh ...

What is the best way to extract the first element of a JSON array in PostgreSQL?

Table Name: table_data_set, Column Name: info Data Format: { "al_uri":"https://al/ma/np_6101", "parameters":[ { "file_name":"QPR.AP6101_%Y%m%d", "input_format":"fixed", "output_format":"parquet", "delimiter ...

Guide to retrieving a .txt file from a separate domain using server-side JavaScript and transferring it to the client side

My goal is to retrieve a .txt file from a web server on a different domain that does not have CORS or web services enabled. I believe I will need to handle this task on the server side using Node.js and JQuery, but I am unsure of where to begin. Currently, ...

Make sure to not update until all the necessary checks have been completed successfully

My goal is to update an array of objects only after all the necessary checks have passed. I have one array of objects representing all the articles and another array of objects representing the available stock. I want to make sure that all the articles ar ...

Retrieving JSON data from the XAMPP localhost in Eclipse

I am new to the world of Android development and programming, and I am currently working on an app that will download a JSON feed from the internet and display it on the screen. Since I don't have access to a server, I am utilizing XAMPP. Based on my ...

Tips for swapping out textures imported from Collada with ShaderMaterial textures in Three.js

Is it possible to update the textures of a basic 3D model loaded using the Collada loader in the Three.js library? My goal is to incorporate color, specular, and normal maps onto the model using ShaderMaterial by referencing new files with the model' ...

Is it possible to initiate an animation in a child component using an input variable?

I have a specific animation that I would like to trigger once an *ngFor loop completes ngAfterViewInit(): void { this.items.changes.subscribe(() =>{ Promise.resolve().then(() => { this.everythingLoaded(); }) }) } After the loop fini ...

Is it possible to conceal my Sticky Div in MUI5 once I've scrolled to the bottom of the parent div?

Sample link to see the demonstration: https://stackblitz.com/edit/react-5xt9r5?file=demo.tsx I am looking for a way to conceal a fixed div once I reach the bottom of its parent container while scrolling down. Below is a snippet illustrating how I struct ...

I am attempting to generate a login system using cookies to verify my access in the database. However, I have encountered an issue where the cookie is not being generated as expected, and I am unsure of where my mistake

As a beginner in the programming world, I'm currently working on implementing a login feature using cookies and local JSON database. Although I'm still learning, I believe I'm making progress in the right direction. Any assistance provided w ...

Using PHP to retrieve JSON data from OpenStreetMap search

I'm attempting to utilize Openstreetmap and PHP to pinpoint a location on a map. Below you can see that I am fetching a JSON array, however, PHP is returning a NULL value. Please note that my $url contains valid JSON (you can validate it here). < ...

Is it possible to apply a class without using ng-class?

Seeking a more efficient way to apply conditional classes to multiple elements on a validation form page, I am exploring options to assign one of five potential classes to each form input. While the traditional method involves manually specifying the class ...