Ajax made Simple Part 5: Asynchronous Calls

In our last Ajax discussion, we discovered that it could take half a second for an Ajax call to complete (actually, due to network latency, it could even be a lot more than that.) How do we do Ajax calls and not make our app look slow?

Easy. We send the Ajax message off, then go do other stuff. When the response comes back, we respond to it. This is called Asynchronous operation.

We do this by adding the name of the function to be called on completion as the 4th parameter of our Ajax call:

req=Ajax("ajax.php/?myText=" + txtSend.value, "", "", done)


Our callback function is called ‘done’. After we execute the Ajax call, the program goes on to the next statement in the program immediately. It doesn’t wait for any response. We can update the screen, or wait for the user to do something else. When the reply comes back, our ‘done’ function will be called:

Function done()
  If req.readyState<>4 Then Exit Function 'ignore progress reports
  If req.status=200 Then 'success
    txtResponse.value=req.responseText
  Else 'failure
    txtResponse.value="Error: " & req.err.message
  End If
End Function

‘done’ will actually be called several times with progress reports on the call. We only care if it completes, so we wait for req.readyState to be 4. The rest of our function works just like when we were not asynchronous.

One of the uses of this technique that we see every day is to return partial results on a search field (as in Google). Each time a character is entered, it is sent to the server for a list of possible matches. As the results come back, the window is updated. Entering characters in the field is unaffected by the server communications that are going on at the same time.

Check out the AjaxAsync app in the Samples to see this in action.