Had the same problem on my S4 mini. Got it solved..
It happens when the charging pin in the port gets bent. Bend it GENTLY and it should work fine..
http://forums.androidcentral.com/samsung-galaxy-s4/287393-samsung-galaxy-s4-charging-issues-can-only-charge-when-phone-off.html