2

How can I make sure that a piece of code has executed completely before executing another? I am sending some ajax requests to a server and then using the returned data to generate the rest of the webpage. the things is, is that i need to have all that data in the webpage to proceed with the rest of the code as that code will affect what has been generated and, that code, runs before the json requests and all of that have finished... is there any way I can make sure this does not happen? I managed to solve it by performing the requests and then asking the user to press a button but that is a total no-sense way of doing it.

Any ideas?

Here is some code: The problem is that the second line is executed before the first (there are many calls to similar JSON functions).

$.getJSON(url, function(data){ $("#mycontent").append("..... stuff here...... create loads of dibs with class set to mydivclass"); });
...
$("div.mydivclass").hide();

Unforunately I cannot use the ajax synchronous property because: "dataType: "jsonp" requests do not support synchronous operations"

2
  • 1
    Can you please post the relevant code fragments? Many functions support callbacks that might come in handy for this purpose. Commented May 21, 2011 at 16:10
  • You don't want to make synchronous calls anyway. If the server is busy you might not get a response right away, which makes the user believe that the browser crashed. Commented May 21, 2011 at 16:24

2 Answers 2

2

If you are using jQuery 1.5+ you can make use of deferreds to solve your issue:

function first_ajax_request() {
    return jQuery.ajax(
         // Your settings here
         success: success_function_1
    );
}

function second_ajax_request() {
    return jQuery.ajax(
         // Your settings here
         success: success_function_2
    );
}

function final_sucess_callback() {
    // Do all your display work.
}

jQuery.when(first_ajax_request(), 
            second_ajax_request()).then(final_success_callback);

There is an excellent article on the topic that you should read up on as well by Eric Hynds. He gives some examples of exactly the kind of problem you are trying to solve.

Sign up to request clarification or add additional context in comments.

Comments

1

jquery requests are asynchonize by default , so your code does not wait for the response , so you have no guarantee that code after request will execute after the response , so you can set the request synchronize by set the async property false , now the request is synchronize and you can gurantee the rest of the code will execute after the response from the server , like this .

$.ajax({
   url: "page.php",
   processData: false,
   data: xmlDocument,,
   async:false,
   success: handleResponse
 });

Comments

Your Answer

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