Though Afghanistan was not colonized it was directly in the center of the Great Game, a large scale strategic conflict in Central Asia, between Russia and the British Empire during the 19th and early 20th centuries. The British in particular meddled in Afghan politics and fought three, not always successful, wars (1st, 2nd and 3rd Anglo-Afghan wars). The second Anglo-Afghan war in 1878-1880 led to the installment of Abdur Raham Kahn as Emir of Afghanistan and effective British control of Afghan foreign affairs until 1919.
In terms of Persia though Russia never exerted the control that the British did in Afghanistan they were still directly involved with Persia in a series of wars (1st and 2nd Russo-Persian wars) which stripped Persia of land in the Caucuses and what is today southern Turkmenistan. The British and Persians also fought a war in 1856 over Herat. Persia was very much hemmed in by the Russian and British expansion to their northern and eastern borders and I believe forced into a series of less than fair trade concessions. They were eventually occupied by the Russians and Ottomans during the 1st world war which led to the fall of the Qajar dynasty. Iran would also be invaded by the Soviets and British in 1941.
So while neither Persia or Afghanistan were colonized they were directly in conflict with European colonial powers. As for why they were not colonized Afghanistan was and is a rugged and isolated region and Persia was a fairly strong and centralized state with a large native population. Neither make for appealing targets for colonization.