What is the best way to trigger a function once another one has finished executing?

After opening the modal, I am creating some functions. The RefreshBirths() function requires the motherId and fatherId which are obtained from the getDictionaryMother() and getDictionaryFather() functions (these display my mothers and fathers on the page so that I can retrieve values in the refreshBirths() function).

I have noticed that the refreshBirths() function is receiving my ids too early, resulting in undefined ids at the end.

While calling my refreshBirths() function in the .done section of the mother/father methods resolves the issue, I prefer explicitly doing it in a specific part of the code.

Even though this solution works, I would rather have the method called elsewhere:

$('#create-modal').on('shown.bs.modal', function() {
  refreshBreeds();
  getDictionaryMother();
  getDictionaryFather();
  $.when(getDictionaryFather()).done(function() {
         refreshBirths();
  });
});

The problem remains unresolved, but I wish to execute that method in a different location.

function getDictionaryMother() {
    $.ajax({
        url: "/admin/api/dictionary/" + "ANIMAL_MOTHER",
        type: "GET",
        dataType: "json"
    })
    .done(function(response) {
        $('#mother-create').empty();
        $('#mother').empty();
        response.forEach(function(mother){
            $('#mother-create').append('<option value='+ mother.id +'>'+ mother.value +'</option>');
            $('#mother').append('<option value='+ mother.id +'>'+ mother.value +'</option>');
        });

        refreshBirths();

    })
    .fail(function(jqxhr, textStatus, errorThrown) {
        displayErrorInformation("Cannot get dict: " + name + " due to: " + jqxhr.responseText);
    });
}

Answer №1

One way to handle Ajax requests is by using the .then() method or the .when() 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

Ensure the first column is fixed and all other columns have the same height

I have encountered an issue where the first column of my table has varying heights compared to the other columns, resulting in inconsistent row heights. Below is the code I am using: <div class="outer"> <div class="inner"> <table> ...

What is causing the Firebase emulator to crash when I run my Express code?

This project is utilizing express.js along with firebase. Whenever attempting to access a different file containing routes, it results in failure. Instead of successful emulation, an error is thrown when running this code: const functions = require(" ...

{"success":true} however, fineuploader displays an error

{"success":true} is returned by the php server script, indicating successful file upload but fineuploader displays an error message in red on the webpage. Upon checking the console, the following error was found: fineuploader-3.2.min.js: [FineUp ...

Fetching data from a Django view using a JavaScript AJAX POST call

Utilizing Javascript for an asynchronous request to a Django View, I am able to successfully receive data from the POST request. However, I am encountering issues with returning a confirmation message that the process was successful. Despite expecting xhtt ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

Automatically advance to the next input field and go back when the backspace key is pressed after reaching the maximum length

Creating a credit card input field that switches cursor after reaching maximum number length and focuses on previous field when deleting with backspace. (function ($) { $(".nmipay-input-field").keyup(function () { if (this.value.l ...

Listener for clicking on a marker in Google Maps

Trying to add a click event to Google Map markers in my Cordova app has proven to be quite challenging. The recommended ways mentioned in the documentation don't seem to work, unless I make the marker draggable - which is not an option for me. It seem ...

Instructions for implementing personalized horizontal and vertical scrolling within Angular 9

I am currently working on an angular application where users can upload files, and I display the contents of the file on the user interface. These files may be quite long, so I would need vertical scrolling to navigate through them easily. Additionally, fo ...

Creating an object using JSON and implementing custom methods in Javascript

When making a $.ajax request to an API, I receive a chunk of JSON data. The JSON looks something like this: var result = { "status": 200, "offset": 5, "limit": 25, "total": 7, "url": "/v2/api/dataset/topten?", "results": [ { "d ...

Integrating eBay API with Node.js

Hello, I am new to Node.js and I could really use some assistance with exporting console log data to an HTML page. I came across a helpful example on GitHub at this link: https://github.com/benbuckman/nodejs-ebay-api My current issue is that although I h ...

Managing data binding for checkboxes within a constantly changing set of options

I'm currently working on designing an angular directive for selecting items from a categorized list. Each item in the list should be selectable using a checkbox. The input data that will be provided to the directive looks something like this: [ { ...

Convert JavaScript code to Google Appscript

Looking for guidance on incorporating Javascript code into my Google Appscript. Here is the code snippet: I have a separate Stylesheet.html file saved. Can someone advise me on how to invoke the functions within the html file? <script> //google. ...

Retrieving a value attribute from the isolated controller of a directive

I have a directive that reads and writes attributes, but I'm having trouble getting it to work as expected. The issue seems to be with the controller inside main-directive.js, which is empty, while the actual action is happening in the isolated direct ...

What could be the reason for the scope being empty in my AngularJS application?

I'm new to Angular and I'm currently customizing the tutorial for my app. However, I'm facing an issue with adding routes to my app. The templates are not being read correctly and the controller seems to have some issues as well. In order to ...

Is it possible to alter the video dynamically according to the state in Vuex?

I am working on a small web application that mimics the appearance of FaceTime. My goal is to switch between video elements by clicking a "Next" button, which will update a value in Vuex and swap out the video accordingly. I initially attempted this appr ...

Tips for repairing a button using a JavaScript function in an HTML document

I am currently working on extracting titles from body text. To achieve this, I have created a button and linked my function to it. The issue I am facing is that when I click on the button, it disappears from its original position. I intend to keep it in pl ...

What sets apart "config" from "defaults" in Sencha Touch?

As a newcomer to Sencha Touch, I have one simple question that's been on my mind... Can someone explain the distinction between "config" and "defaults" in Sencha Touch? ...

What is the proper way to incorporate a hashtag (#) into a PHP parameter within a URL

Currently, I am sending a PHP request to a login handler using the following URL: https://example.com/test.php?username=test123&password=hiuhsda3#24 However, I need to retain the hashtag in either the password or username along with anything that come ...

Converting php array submitted from a form using ajax

I have a form on my website that collects user input and sends it to an email address using php. The form includes a checkbox input where users can select multiple options, which are then stored in an array. However, when the form is submitted, the email r ...

Storing TypeScript functions as object properties within Angular 6

I am working on creating a simplified abstraction using Google charts. I have implemented a chartservice that will act as the abstraction layer, providing options and data-source while handling the rest (data retrieved from a REST API). Below is the exist ...