4n35 Optocoupler as Switch

The IRF510 is a N channel device, it will not work as a high side switch. You need a p channel device wired something like this: