Assalaamu alaykum wa rahmatullaahi wa barakaatuh. I was praying in the masjid behind the mam, and we were prostrating. There was a fly crawling on the floor. I got scared and lifted up my head, at the same instant, by coincidence, the imam said the Takbeer (saying: Allahu Akbar [Allah is the Greatest]). Is this ok, given that I did not raise my head for Allah but because I got scared of the fly?
All perfect praise be to Allah, the Lord of the worlds. I testify that there is none worthy of worship except Allah and that Muhammad, sallallahu ‘alayhi wa sallam, is His slave and Messenger.
Since you raised your head from the prostration because you were scared – not with the purpose of rising from it – this is insufficient in terms of clearing you of your liability from the obligation, and you have to return to prostration and then raise your head from it. The Shaafiʻi book Al-Iqnaaʻ fi Hall Alfaath Abi Shujaaʻ reads, "He must not intend, by raising his head from prostration, something else ... If he raised his head out of fear of something, it is insufficient and he must return to the prostration."
The Kuwaiti Encyclopedia of Fiqh reads, "If he raised his head because he got scared of something, it is insufficient and he must return to the prostration. The Hanbalis also held this view and said: it is a condition in performing the bowing and prostration and in rising from them that he does not intend otherwise. If he performed the bowing or prostration or rose from them out of fear of something, it is insufficient. It is also not a condition that he intends these actions per se, as the intention for performing prayer is sufficient."
Hence, your prayer was invalid, and you are obliged to repeat it.
Allah knows best.
You can search for fatwa through many choices