Balkh was nominally ruled by Mahmud Khan, the former khan of Western Karakhanids, but the real power was held by Muayyid al-Din Ay Aba, amir of Nishabur for three years. Sanjar finally escaped from captivity and returned to Merv through Termez. He died in 1157 and control of Balkh passed to Mahmud Khan until his death in 1162. It was captured by Khwarezmshahs in 1162, by the Kara Khitans in 1165, by the Ghurids in 1198 and again by Khwarezmshahs in 1206.