If I call this function directly it works fine, yet if I call it from Javascript using an ajax call it wont work correctly.
I found out the reason for this, it was cause I was using $(document).ready(function ..) where I should call the functions directly after the ajax returns the results.