Replacing existing ceiling fan but there’s no junction box
Indeed this is a code violation and shows that some previous cowboy owner or DIYer installed it in an inappropriate manner. 

To get this right you would have to install an electrical box rated for hanging a fan mounted in the ceiling. The box should have a built in or applied cable clamp to secure the wire. 

If you have access to the attic area above this ceiling the best way I've used to secure the electrical box in place for hanging a fan or heavy lighting fixture is to cut several pieces of wood that span across the ceiling joists as shown in the picture below. The top piece is screwed to the upper side of the joists and the lower piece is screwed to the upper piece. The lower piece is typically part of a 2x4 ripped for width and sits on edge under the flat upper 2x4. After careful measurement and cutting the two pieces can be pre-assembled before installing over the electrical box hole.