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