Chlorine is a highly electronegative element, which means that it has a strong tendency to attract electrons. In order to bond with chlorine, an element must be able to give up its electrons easily. This is a property that is characteristic of metals.
Na and Mg are both metals. Na is a very reactive metal, which means that it gives up its electrons very easily. Mg is a less reactive metal, but it still gives up its electrons more easily than chlorine. This means that both Na and Mg are able to bond ionically with chlorine.
The other two elements, C and O, are nonmetals. This means that they do not give up their electrons easily. In fact, they have a strong tendency to attract electrons. This means that they are unable to bond ionically with chlorine.