The origin of the slogan are in Takenouchi Shikibu's theory of absolute loyalty to the Emperor (尊皇論 sonnōron), with the implication of being less loyal to the ruling Tokugawa Shogunate. Expelling the barbarians, on the other hand, was a counterreaction to the Treaty of Kanagawa, which opened Japan to foreign trade in 1853. Under military threat from Commodore Matthew Perry's black ships, the treaty had been signed under duress and was vehemently opposed in samurai quarters.
The slogan was adopted as the battle cry of the rebellious provinces of Choshu and Satsuma. The Imperial court in Kyoto unsurprisingly sympathized with the movement and in fact rather ineffectually ordered the Shogunate to sonnō jōi in 1863. Masterless samurai (ronin) rallied to the cause, assassinating Shogunate officials and Westerners, and culminating most famously in the murder of the British trader Charles Richardson.
But this turned out to be the zenith of the sonnō jōi movement, since the Western powers responded by demanding heavy reparations and then bombarding Satsuma capital Kagoshima when they were not forthcoming. While this incident served to further weaken the shogunate, permitting the rebel provinces to ally and overthrow it in the Meiji Restoration, it also clearly showed that Japan was no match for Western military might.
It is worth noting that the slogan was never actually government or even rebel policy; for all its rhetoric, Satsuma in particular was a large trading partner who purchased guns, artillery, ships and other technology from the West. After the symbolic restoration of the Meiji Emperor, the slogan was quietly dropped and replaced with another: fukoku kyōhei (富国強兵), or "rich country, strong military", the rallying call of Japan's wildly successful Meiji Era and the seed of its actuions during World War II.