Execute a function once the previous function has finished its execution

I am attempting to accomplish the following:

function doThis()
{
    firstFunction(function()
    {
        closeWindow();// close window only after firstFunction() completes
    });
}

doThis() is invoked from a button. The firstFunction() is an AJAX call and upon its completion, a second non-AJAX function called alert() should be executed. However, it seems that the code is not working as expected. The firstFunction() is functioning properly and being invoked correctly. But the window.close action does not seem to be triggered.

Any suggestions? No jQuery solutions please.

update:


Let me provide more details on this. The doThis() function is called from a submit link.

<a href="#" name="sumbit" onClick='doThis()'><img src="img.png"/></a>

After clicking this link, the form should be submitted and the popup window closed. The firstFunction() uses XMLHttpRequest to POST the form and works fine when used like this:

<a href="#" name="sumbit" onClick='firstFunction()'><img src="img.png"/></a>

With doThis(), I am trying to submit the form first and then close the popup but haven't been successful.

update 2


As delnan pointed out, it appears that firstFunction was not executing the function passed to it as an argument. I made some changes and now it functions properly:

function firstFunction(callback)
{
//do ajax stuff
callback(); //calls closeWindow()
}

Thank you all!

Answer №1

Do you have confidence in the functionality of your AJAX code? How can you verify this without the callback function being executed? You may consider passing just an alert statement directly to firstFunction instead of wrapping it in a separate function.

Answer №2

To define your function, use the following syntax:

function myFunction(callback) {
     // set up XMLHttpRequest or equivalent for IE
}

Within the readystatechange event handler, invoke the callback like this:

if(this.readyState == 4 && this.status == 200) {
     // other actions
     callback();
}

If you have already implemented this and are still encountering issues, there may be an error within the myFunction that needs to be addressed.

Alternatively, ensure that doThis is being properly called.

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

Choose a specific example using the class name in nicEdit

Is there a way to select an instance using nicEdit based on its class name rather than just its id? For example: <div class="myInstance1"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed magna dolor, faucibus ac, iaculis non, cursus et ...

Utilizing loop variables in ng-class and ng-click directive

This piece of code generates a list consisting of seven thumbnails, with the currently active image designated by the active and thumb classes. <div ng-repeat="no in [1, 2, 3, 4, 5, 6, 7]"> <img ng-src="images/{{no}}t.jpg" class="thumb" ng ...

Changing Table Cell Color with Bootstrap Based on Value

I have implemented Bootstrap tables into my project using the tables provided on this website Bootstrap Tables and I am populating data from my MongoDB to these tables. One of the fields in my table is labeled "ACTIVE" and I am looking for a way to dynami ...

In my coding project using Angular and Typescript, I am currently faced with the task of searching for a particular value within

I am facing an issue where I need to locate a value within an array of arrays, but the .find method is returning undefined. import { Component, OnInit } from '@angular/core'; import * as XLSX from 'xlsx'; import { ExcelSheetsService } f ...

Is there an equivalent to Android's addJavascriptInterface() for desktop webkit browsers?

In my quest to explore Android UI capabilities, I stumbled upon the addJavascriptInterface() method documentation that enables the exposure of methods on an Android Java object to Javascript within a WebView component. The concept of bridging the gap betw ...

Updating website content dynamically using Javascript and JSON-encoded data

My programming code seems to be acting oddly. I have structured my data in a JSON object as follows: injectJson = { "title": "Champion Challenge Questions", "rules": [ { "idChrono": "chrono-minute", "text": "Top is missing!", ...

jquery: accessing the values of an array of select box inputs

When the button is clicked, I want to retrieve the selected value from multiple select boxes. Although I can successfully fetch values from an array of textboxes, I am encountering difficulties in retrieving the select box value as it returns an empty ar ...

Guide to clicking on elements with selenium framework

Struggling to scrape a web page from the bookmyshow site using selenium. Encounter two popups upon loading the page, trying to click the necessary buttons to close them. Facing issues locating these elements despite using sleep() to ensure complete page lo ...

In Firefox, the event.preventDefault() function is not functioning as expected

I'm trying to utilize the function below to prevent the default action, such as "a href", but I'm running into issues specifically in Firefox. function alertPopup(html) { event.preventDefault(); // ... } After attempting to add the vari ...

Incorporating arguments within the context of a "for each" loop

I'm attempting to develop a straightforward script that converts RGB-16 colors to RGB-8. The script is functioning properly, but I'm having trouble converting it into a function that can handle two different palettes. Whenever I try using palette ...

Obtain user input and extract the name using jQuery's serialization function

Trying to extract user input from a dynamic form using jquery serialize. The structure of my form is as follows: <form id="lookUpForm"> <input name="q" id="websterInput" /> <button onclick="webster(); return ...

Attempting to retrieve information from my MongoDB database and populate it into a <table> structure on a web page

My objective is to extract data from a MongoDB database and display it in an HTML table. Specifically, I am trying to retrieve information from the hangman database's players collection, which contains fields for name and score. Can anyone help me ide ...

Error: EPERM -4048 - the system is unable to perform the operation specified

Every time I attempt to install a package using npm install, I encounter an error message (usually referring to a different path). I have attempted running npm cache clean, restarting my computer, and checking for any processes that may be interfering with ...

Having trouble integrating an HTML template using JavaScript

I am currently attempting to integrate the HTML code of my website using data-prototype: <div id="accordion" data-prototype=' <div class="card-body"> <textarea id="solution_answers___name___content" name=& ...

Utilizing lodash for extracting specific values from an object and formatting them as a string separated by pipes

Using Lodash, I am trying to extract values from an object while excluding specific fields. Consider the object below: var x = { id: 0, // <-- id is excluded from output a: 1, b: 2, c: 3 }; In real-world scenarios, objects are typical ...

Attempting to utilize ajax in Laravel, however encountering a 404 error

Trying to retrieve data through JSON using AJAX. Controller: public function getFreeDay(Reservation $reservation): JsonResponse { //other data will be here, this is just for testing try { return response()->json([ 'stat ...

Is there a way to access the $state.current.name from a statechange event in ui-router?

I want to retrieve the .state('name') when switching locations in angular. Within my run(), I can access the $state object: .run(function($rootScope, Analytics, $location, $stateParams, $state) { console.log($state); However, attempting ...

What is the location to enable devtools for vue.js?

Here is the main.js file of my Vue app: import VueResource from 'vue-resource' import VueRouter from 'vue-router' import Routes from './routes' import App from './App.vue' import Vue from 'vue' import &apo ...

Unleash the full power of Angular Components by enhancing them with injected

I am facing a challenge with handling the destruction event of an Angular component in my external module that provides a decorating function. I've run into issues trying to override the ngOnDestroy() method when it includes references to injected ser ...

Adding a list of items into a PostgreSQL database using SQL syntax

I need to perform multiple table inserts, where the last table relies on the one before it and includes an additional list of items. I am working with pg in conjunction with node.js and JavaScript. Table 1: insert into col1, col2 values (1, 2) return col1 ...