Actions are judged by intentions
رَوَاهُ إِمَامَا الْمُحَدِّثِينَ أَبُو عَبْدِ اللهِ مُحَمَّدٌ بنُ إِسْمَاعِيلَ بْنِ إِبْرَاهِيمَ بنِ الْمُغِيرَةِ بنِ بَرْدِذْبَهْ الْبُخَارِيُّ وَأَبُو الْحُسَيْنِ مُسْلِمٌ بنُ الْحَجَّاجِ بنِ مُسْلِمِ الْقُشَيْرِيُّ النَّيْسَابُورِيُّ فِي صَحِيحَيْهِمَا الَّذَيْنِ هُمَا أَصَحُّ الْكُتُبِ الْمُصَنَّفَةِ.
On the authority of the Commander of the Faithful, Abu Hafs Umar ibn al-Khattab (may Allah be pleased with him), who heard the Messenger of Allah (may Allah bless him and grant him peace) say: "Actions are but by intentions, and every man shall have only that which he intended. So he who emigrated to Allah and His Messenger, his emigration is to Allah and His Messenger; and he who emigrated for some worldly gain, or for a woman he wished to marry, his emigration is to that for which he emigrated."
The hadith is related by the two imams of the hadith scholars, Abu Abdillah Muhammad ibn Isma'il ibn Ibrahim ibn al-Mughira ibn Bardizbah al-Bukhari and Abu al-Husayn Muslim ibn al-Hajjaj ibn Muslim al-Qushayri an-Naysaburi (may Allah have mercy on them), in their two Sahihs, which are the soundest of compiled books.
[al-Bukhari 1; Muslim 1907]