1

i have a quick question. I want to iterate over all checked checkboxes and parse the json files for the checked ones.

Here is my problem: The $().each function is synchronous and the $.getJSON() function is asynchronous. So i know i would have to pause the exectuion of the each() loop until the JSON File is parsed. How can i pause the loop? Or any other ideas solving this problem? Thank you very much.

$("input:checkbox[name=check]:checked").each(function()
{
    $.getJSON( $(this).val(), function( data ) {
        //Do smth.
        //Pause the each loop?
    }).error(function(jqXhr, textStatus, error) {
            alert("ERROR: " + textStatus + ", " + error);
    });
}); 
alert("foo"); //<-- gets executed before all json files are parsed.
6
  • Why would you need to pause the each loop? What are you doing with data returned from server? Commented Apr 26, 2014 at 15:10
  • The JSON Files contain questions. And i want to check how many questions in all selected json files are. So instead of alert("foo"); i want to check how many questions in the parsed json files are contained. Right now the each function is finished before even the first json file is completly parsed. Commented Apr 26, 2014 at 15:19
  • You should look into deferreds see this example. Commented Apr 26, 2014 at 15:20
  • First, collect all the checked boxes. Then send this as an array or JSON to your backend. Send back one answer and do your stuff in the callback of your AJAX function. Commented Apr 26, 2014 at 15:23
  • @Nils you should read: stackoverflow.com/questions/14220321/… Commented Apr 26, 2014 at 15:29

1 Answer 1

-3

If you want to make the AJAX request synchronouse, pass async config as false.

$.ajax({
  dataType: "json",
  url: 'your URL',
  async: false,
  success: success
});

Documentation

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

7 Comments

Users usually don't like freezed UI
The question is about pausing the execution of the loop until the AJAX completes. 'async' does the job.
@SelvarajMA it does do the job, but it uses the worst practice and may deadlock the browser (or the tab) if anything goes wrong (I down voted).
this was exactly what i needed. The "freezed" UI is something i can deal with. I will show a the loading indicator. Thank you very much!
@PhistucK SO is about answering the question. Not for preaching what you believe. And please look at Nil's comment above. Everyone has their own requirements.
|

Your Answer

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.