This is called front running. Whether it is legal or not depends on whether it is based on public or private information. If a broker does it on the basis of a client's order, it's unethical, illegal, and subject to all sorts of sanctions, though certainly not impossible. If a a high frequency trader (HFT) pays for fast computer access to multiple exchanges, and your order cannot be filled on a single exchange, it's entirely legal for them to observe your order come in on one exchange, and front run it on other exchanges, taking advantage of their faster connection and superior computer power.
Ordinary retail trading in individual stocks doesn't usually have to worry about this. Nobody is going to front run a tiny order of 100 shares. Front running only makes sense when orders are so large that they will move the market. Also, small orders are typically filled on a single exchange, so there's limited opportunity for a HFT to insert themselves in the trades.
There is an issue for retail traders investing in mutual funds. Mutual funds do place huge, market moving orders, which pull shares from multiple exchanges. These trades are vulnerable to front running by HFT, driving up the costs of the purchases, and marginally reducing the returns of retail buyers of the fund. Whether this is fair or ethical is a matter of debate. Some claim that the exchanges are essentially selling HFT the right to "tax" high volume trades. Others claim that HFT is no different than the other tools traders have used over hundreds of years to gain an information advantage. One hundred years ago it was access to a trans-Atlantic telegraph line. Now it's a private optical fiber link to the exchange.