Waiting for the response of a Javascript function

I have the code snippet below:

myFunc();
bar();

The function myFunc() initiates an ajax request.

I want to ensure that bar() is only executed after myFunc()'s ajax request has been completed.

However, I do not wish to move the call to bar() inside of myFunc.

Is this possible?

EDIT

Below is the revised code that addresses this issue:

var FOO = {
 init: function(blah)
 {
  // Callback functions to be passed when loading challenge data via AJAX
  var callbacks = {
   myFunc1: function(){ myFunc1(blah); },
   myFunc2: function(){ myFunc2(blah); },
  };

  this.bar(callbacks); // Load challenge data and set up the game
 },
 bar: function(callbacks) { ..iterate through and execute them.. }

};

Answer №1

If you want to achieve the desired outcome, it is essential for bar() to establish communication with myFunc().

When expressing your preference against moving the call to bar() inside myFunc(), there are various ways to interpret this.

For instance, you have the option of turning bar() into a parameter of myFunc()

function bar() {
   // perform actions specific to bar()
}

function myFunc(callback) {
   // utilize the callback function in the xmlhtprequest object's onreadystatechange property
}

myFunc(bar)

I trust that this explanation proves useful to you

Sincerely, Jerome Wagner

Answer №2

Adding a flag to signal the completion of myFunc() is possible, but it's not recommended. Instead, best practice is to utilize callbacks.

Consider trying out this code:

var requestSuccess = false;
myFunc(); // set requestSuccess to true upon successful response

var pollingInterval = setInterval(function() {
    if (requestSuccess) {
        clearInterval(pollingInterval);
        executeCallback();
    }
}, 100);

Answer №3

Sorry, it's not feasible unless you opt for a synchronous request, but that would no longer fall under AJAX. I highly advise against this approach as it will cause the UI to freeze until the request finishes, resulting in a poor user experience due to browser freezing.

Answer №4

Unfortunately, that won't work.

If you attempt to accomplish it by using a SJAX request instead of AJAX, the browser will freeze up as a consequence - so it's not recommended at all.

Embrace event driven programming while working within an event driven environment for better outcomes.

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 halt a CSS transition using JavaScript when dealing with an image?

I am facing an issue while attempting to create a basic CSS transition using JavaScript. The goal is for the start button to trigger the movement of an element, based on the duration of the keyframe animation. Then, clicking the end button should make the ...

Transferring files with Node.js via UDP connections

I'm currently working on setting up a basic Node.js server that is designed to receive files from clients through UDP. The challenge I'm facing is that whenever I attempt to send a large file (anything over 100kb), the server appears unresponsive ...

Exploring AngularJS JSON Parsing Techniques (such as utilizing ng-repeat)

My approach to processing json data looks like this: $scope.activities = response.data; console.log($scope.activities.length); var list = []; for (var i = 0; i < $scope.activities.length; i++) { console.log($scope.activities[i].name); list.pus ...

What steps do I need to take to set up CORS properly in order to prevent errors with

I encountered the following error message: "Access to XMLHttpRequest at 'api-domain' from origin 'website-domain' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HT ...

Get information collectively in node.js

How can I retrieve 10 records from a MongoDB collection using NodeJs, with each batch containing 10 records? ...

Origin Access-Control-Allow Not Recognized

Currently, I am developing a node.js app and have encountered a strange issue: This particular Angularjs snippet... // delete hosts $scope.delete = function(row) { var rowData = { hostname: row.hostname, ipaddr: row.ipAddress, ...

Can I apply a universal babel configuration across all of my personal projects?

It becomes tedious to duplicate the same configuration file for each new project I start. ...

Matching numbers that begin with zero or are completely optional using Regex

Attempting to come up with a regex pattern that will allow the entry of the specified input into an HTML input field: The input must begin with 0 The input can be left empty and characters may be deleted by the user ^[^1-9]{0,1}[0-9\\s-\& ...

Issues with Bootstrap Navigation Collapse Utilizing Data Attributes

I'm having trouble getting a Twitter Bootstrap 3 navbar to collapse using data attributes, as it is not expanding properly. Just to give some context, the project I am working on is an ASP.NET C# MVC project that runs on DNN (DotNetNuke) CMS. When I ...

Issues with functionality of an HTML form select utilizing jQuery

I have implemented the following code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> <select name="cars" id="dynamic_select"> <option value="http://www.visionabacus.com/Australia/1/SuiteA ...

Is there a way to retrieve the initial value from the second element within the JSON data?

Exploring JSON Data Collections In my JSON data, I have two collections: FailedCount and SucceededCount. { "FailedCount": [{ "FailedCount_DATE_CURRENT_CHECK": "2016-11-30 10:40:09.0", "FailedCount_DATE__CURRENT__CHECK": "10:40:09", "FailedCo ...

Confusion arises between Bootstrap button plugin and Vue checkbox click event

After incorporating bootstrap.min.js into my Vue app, I noticed that the checkboxes' @click event is no longer triggered. This issue specifically occurs when using bootstrap's button-group with data-toggle="buttons". If I remove bootstrap.min.js, ...

Access numerous data points using ajax and php, sans the need for Jquery

Exploring website coding has been an amazing journey for me, and I've come to realize that JavaScript and Ajax play vital roles in creating a standout website. However, my internet research didn't yield very helpful results. Most of the code exam ...

Utilize three.js within a Google web app script - unable to incorporate the script module type for loading three.js

Looking to incorporate three.js into a Google Web Script to load 3D CAD files, I discovered that the installation instructions on threejs.org specify the script needs to be of "module" type. However, after researching for several days, it seems that Google ...

Converting Numerical Formats into Numbers: A Step-By-Step

How can I format numbers in JavaScript as 1,000,000 without being able to use the operators +, -, *, or / with numbers inputted into a specific box? After clicking "try it," an error message is displayed: ORIGINAL AMOUNT: NaN ORIGINAL AMOUNT: NaN ...

Duplicate an $sce generated entity and adjust its content

I am facing a situation where I have a variable structured in the following way: tableData1[$scope.tableHeadingsConstant[0]] = $sce.trustAsHtml('<div class="header12" id="runTitle0" style="cursor: pointer;">' + counter ...

Attempt to implement the Woocommerce cart update link using Timber after performing an Ajax request

I'm currently utilizing the amazing Timber plugin for Wordpress and attempting to implement this Gist using a Twig Template, but so far I've been unable to make it work. The code in my functions.php appears like this: function my_wc_cart_count( ...

Identify the mistake using the callback function

My middleware was developed to utilize an external code for managing user accounts. When creating a new account, I rely on the Manager's function with the following code snippet: .post(function(req,res,next){ UsersManager.createUser(req.body. ...

JS asynchronous function failing to update variable

let encodedAccount = ''; function encodeUsername() { encodedAccount= encryptValue(document.getElementById('account').value); alert(encodedAccount); } The encryptValue function is an asynchronous AJAX function. The alert method ...

Building a Multi-Language React Application with Real-Time Data

Is there a way for users to input data in their chosen language (English, French, German) and have that data saved in all three languages in the Database so they can view it based on their language selection? I've experimented with React-Intl and I18 ...