Since the request is executed in asynchronous mode (and you really do not want to do this in synchronous mode, since it freezes the browser during the whole time of the request), you have absolutely no way to know when the request will be completed:
Run the query with
$.ajax({ ... }); // "here"
But the request runs in the background and is not completed when you reach βhereβ.
In order to be able to work with the "return value" of the Ajax request, you must do all your work inside the function connected to the success event (or complete or any event you want).
Instead of just putting msg.d in nUnratedCount , this function really should work with it (for example, displaying it in an HTML document or whatever you want to do with this piece of data)
source share