1

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#?

kpmDev
  • 1,330
  • 1
  • 10
  • 28
Scott
  • 5,338
  • 5
  • 45
  • 70

3 Answers3

3
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);
}
Preston S
  • 2,751
  • 24
  • 37
  • @RajaprabhuAravindasamy Sometimes Javascript is finicky and needs to be told to wait before doing something. Using setTimeout with a delay of 0 tells the browser to wait for everything to finish before doing anything else. Great explanation here: http://stackoverflow.com/a/779785/382456 – Scott Jan 23 '14 at 05:05
  • 2
    @RajaprabhuAravindasamy Kind of, using setTimeout invokes the method on a fresh call stack. I used it here to prevent the possibility of stack overflow or too much recursion exception. – Preston S Jan 23 '14 at 05:06
2

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.

Ted Bigham
  • 4,237
  • 1
  • 26
  • 31
0

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');
        }
Airan
  • 477
  • 2
  • 13