3

To consolidate a few SQL calls I'm trying to make one query to the server and then have the client side iterate through each result. The caveat is that I need to wait for user input before processing the next result. Is this possible?

I have a jquery call similar to below:

$.post('functions/file_functions.php', {type: 'test', f: 'load'}, function(data) {
    if (data.success) {
        $.each(data.files, function() {

            // Can I wait for user input at this point and then process the next
            // file after a users interaction (e.g. a button click)?

        });
    }
}, "json");
Paul
  • 11,671
  • 32
  • 91
  • 143

2 Answers2

4

I'm going to expand on my comment a bit, and hopefully make it a useful answer. JavaScript is single-threaded, so there's no way to block the execution of a function while waiting for something else (such as an element being clicked on) to happen. Instead, what you could do is store the list of files into an array when the AJAX POST request returns successfully, then use a separate click event handler to cycle through them (I assume getting one file per click).

Code may look something like this:

$(function() {
    var files, index = 0;

    $.post('functions/file_functions.php', {type: 'test', f: 'load'}, function(data) {
        if (data.success) {
            files = data.files;
        }
    }, "json");

    $('.mybutton').click(function() {
        if(files) {
            var file = files[index++];
            // do something with the current file
        }
    });

});
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0

One of the ways to have "blocking" user input in javascript is to call window.prompt (among others like window.confirm, or window.showModalDialog). However its not really customizable, you might want to just save the data coming back from the server and have some kind of a user input event based processing.

In code it would look like this:

var the_answer = window.prompt("What's the airspeed velocity of an unladen swallow?");
console.log(the_answer);
complex857
  • 20,425
  • 6
  • 51
  • 54
  • [`window.showModalDialog`](https://developer.mozilla.org/en/DOM/window.showModalDialog) is also blocking. – Rob W Aug 03 '12 at 13:12
  • Sure, just like `alert` and `confirm` and others, but that's not really for getting user input. – complex857 Aug 03 '12 at 13:21
  • `confirm` does actually request user input (although it can has only two different values). `showModalDialog` can be used to request any user input. Inside the modal window, set `returnValue` to **any** value (arrays for example), and it will be passed to the opener. In Chrome, there's a bug with the implementation, but there's an [easy work-around](http://stackoverflow.com/a/10234548) to it. – Rob W Aug 03 '12 at 13:27