When Gandalf died, his spirit went to Iluvatar (The god of the Tolkien universe) and was sent back to Middle Earth stronger and smarter. He was given this second chance because he was the only wizard who was genuinely fulfilling his task and he sacrificed himself for his friends.