Tips & Tricks in programming for noobs
Today’s article: Tips for making successful Ajax calls
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.