Grammatically, they both work. The only reason I can think of for
ついで being wrong is a little nitpicky, but it does highlight an important nuance of this word.
ついでに is very hard to translate appropriately. The concept is similar to the “while you're at it” in “While you're at it, could you do this too?”. It is to take the opportunity to do something else, since you've already done something similar, or in close proximity.
This makes sense if you are able to buy coffee on the way to/from (or somewhat nearby) the pharmacy.
I won't say this is blatantly wrong, but it is a little strange in most situations. You usually go to the pharmacy for the exact purpose of buying medication. This doesn't really fit the concept of
Perhaps this is what the textbook wanted to point out. おみやげ, by their very definition, are exactly what you buy on trips to bring home. In exaggerated terms, it's like saying you went to the zoo, and ついでに looked at some animals.
It would make more sense if there was a different noun in place of the おみやげ. For example, she gets cosmetics for you: