Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I wait for input from the client side after a server side query?

Tags:

jquery

php

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");
like image 232
Paul Avatar asked Jan 28 '26 18:01

Paul


1 Answers

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
        }
    });

});
like image 90
Anthony Grist Avatar answered Jan 30 '26 09:01

Anthony Grist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!