Added check to ensure the ajax query yielded results before looping on a possiby undefined array