Scott
Scott

Reputation: 5369

Using jQuery AJAX requests in a while loop

The following code will ask the user to enter their name, send it off to a processing script (saves to database, validates, etc) and returns a response:

var invalid = true;
while (invalid) {
    var name = prompt("Enter your name");
    $.ajax({
        type: "POST",
        url: "save.php",
        data: {
            "name": name
        }
    }).done(function(e) {
        //in this example, save.php returns "invalid" if the input did not pass validation
        invalid = e === "invalid";
    });
}

You can see the general idea I'm going for, but the problem is this: Even if I make the AJAX call synchronous, it doesn't block the loop from continuing. Placing a console.log in the done function reveals that the loop runs about 200 more times until my server gives a response.

The server does a heavy amount of calculations on the user's input - I'm just using name as an example here. This cannot be done client-sided. How can I implement this simple, beginner's design pattern across what is essentially reminding me of my multithreading nightmares in C#?

Upvotes: 1

Views: 2480

Answers (3)

Airan
Airan

Reputation: 477

That just worked great for me. I hope it works for you too.

        var invalid = true;
        while (invalid) {
            var name = prompt("Enter your name");
            console.log(Date()+' Start Loop');
            $.ajax({
                 type: 'POST',
                 data: {'name': name},
                 async: false,
                 url: yourURL
            }).done(function(e) {
                //in this example, save.php returns "invalid" if the input did not pass validation
                console.log(Date()+' Done()');
                invalid = (e === "invalid");
            });
            console.log(Date()+' End Loop');
        }

Upvotes: 0

Preston S
Preston S

Reputation: 2771

function validate(e)
{
    if(e === "invalid")
        setTimeout(submitName, 0);
}

function submitName()
{
    var name = prompt("Enter your name");
    $.ajax({
        type: "POST",
        url: "save.php",
        data: {
            "name": name
        }
    }).done(validate);
}

Upvotes: 3

Ted Bigham
Ted Bigham

Reputation: 4341

Instead of a loop, just re-trigger the input from the done() code. You'd probably want to name this function so it can refer to itself.

Upvotes: 2

Related Questions