3

I have a problem understanding how this could/should be solved.

I have two functions. In the first function ( I call it loadData() ) I'm doing an asynchronous request to the server to load some data.

In the second function ( saveData() ) I'm also doing an asyn request to the server to write some data. In the callback of this request I'm calling loadData() to refresh the data.

Now the problem: In the saveData() function I want to wait for loadData() to be finished before I show a dialog (like alert('Data saved'))

I guess this is a common problem, but I couldn't find the solution for it (if there is one..)

A solution would be to make the requests synchronous, but the framework I'm using doesn't offer that and I hope there's a better solution..

Thanks to all!

Mahmoud Gamal
80.3k18 gold badges143 silver badges168 bronze badges
asked Jun 10, 2010 at 10:47

2 Answers 2

10

The trick in these situations is to nest the "success" callbacks like this:

$.ajax({ 
 url: "/loadData", 
 success: function () {
 // Data Loaded... Save the data
 $.ajax({ 
 url: "/saveData", 
 success: function () {
 // Data Saved... Display alert
 alert('Data saved');
 }
 });
 }
});

If your loadData() function looks something like this:

function loadData() {
 .ajax({ 
 url: "/loadData", 
 success: function () {
 // Data Loaded... Process the data
 }
 });
}

... then you may want to give it a callback argument that gets invoked just before the success callback returns:

function loadData(myCallback) {
 .ajax({ 
 url: "/loadData", 
 success: function () {
 // Data Loaded... Process the data
 // ... Your Data Processing Logic ...
 // Invoke the callback (if one was passed):
 if (typeof myCallback === 'function') {
 myCallback();
 }
 }
 });
}

Then you would be able to implement your saveData() function like this:

function saveData() {
 loadData(function () {
 // Data Loaded (and processed by loadData())... Save the data
 .ajax({ 
 url: "/saveData", 
 success: function () {
 // Data Saved... Display alert
 alert('Data saved');
 }
 });
 });
}

You would still be able to call the loadData() function without any arguments in other parts of your script.

answered Jun 10, 2010 at 10:53
Sign up to request clarification or add additional context in comments.

Comments

1

Nesting functions is a solution but is a bad idea when it comes to code quality. You may want to take a look to jquery deferred object to solve it.

Deferred documentation

answered May 9, 2013 at 17:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.