Tips & Tricks in programming for noobs

Today’s article: Tips for making successful Ajax calls

Ajax (i.e Asynchronous JavaScript and XML) allows you to communicate with server’s without having to reload an entire web page thus ensuring flawless user experience. However, the very asynchronous nature of Ajax, sometimes, put newbies in perplex state as they get unexpected results.

For example, you must have tried the following code and got undefined response.

Now, you are wondering why did I get undefined?

Well, to put this in simple words, code execution will not stop after browser makes an Ajax call. We may or may not have received response when line 19 is being executed. A possible workaround for this issue is given below:

The idea here is to put your code inside success callback. It will only be executed upon receiving response from the server. Please note that “End” may get print before your success callback even starts executing. I don’t recommend this approach because you may have functions or large code inside success callback if you are working in a big project.

I would recommend the following approach:

Success and error callbacks need not to be only anonymous functions. You can create named function and map them to callbacks. This promotes clean code and code readability. Ajax will take care of passing the necessary arguments to named functions.

I hope you liked my article, and it helped you in one way or the other. You can follow me on twitter or Facebook.