You should not use when or success . It looks like (although the code examples would be clearer) you attach two separate listeners to the ajax call, but you want it to execute only after the other.
I would either throw both at the same event, for example:
$.ajax( ... , function(){
Or wrap the ajax call in another promise (this might require a bit more reading around jQuery promises).
But if you do something like
$.when($.ajax( ... , function(){
Thing a and b will be executed at the same time, because they are designed for almost the same thing.
source share