user7435747
user7435747

Reputation: 487

Why a request value instantly returns empty before I enter something in it?

here I have a code:

$foo = $this->request['value'];
if (empty($foo)) {
    return 'error message';
}

A situation is that I need to check if a variable is empty, but I need to check it after I click on a submit button.

What's happening now is that when I load the page, it instantly says that it's empty (because it is empty) and brings the error message for me even if I haven't entered something in it, but how to do it that it would check after I enter something in it?

Upvotes: 0

Views: 59

Answers (1)

cmprogram
cmprogram

Reputation: 1884

You need to check that your form has been posted.

Remember that PHP code is executed server-side. So the code is executed and performed once when you refresh your page (excluding AJAX requests etc which can come later via JavaScript).

So your page is loading, your checking if a value is empty, and since you haven't set it to anything, it returns this message.

Check if on page load, it has been sent their via a form, and contains POST content.

if(isset($_POST['a_value_from_your_form'])){

$foo = $this->request['value'];
if (empty($foo)) {
    return 'error message';
    }

}

Upvotes: 1

Related Questions