The best way is to use states. The moment the player pushes space, you apply an upwards force and change their state. In the new “jumping” state, you do not look for the space bar, only if the ground is underneath them, upon which you revert to the normal first state.
make the jump (a strong upward “force” not “loc”) dependent on 2 sensor: spacebar and a short -Z oriented ray, connect them using an “and” controler. If you do that the character will only jump when you press spacebar AND when there is something under his feet.
This might not work the first time: you have to tweak the ray length and the upward force strength depending on the object mass