I\'m trying to work with AJAX autocompletes and I am having a few problems with getting the two languages to work in synergy.
When I replace all the issets with only
You just need:
if (!empty($_POST['search_term']) && !empty($_POST['postcode']))
isset && !empty
is redundant.
The parameters of isset()
should be separated by a comma sign (,
) and not a dot sign (.
). Your current code concatenates the variables into a single parameter, instead of passing them as separate parameters.
So the original code evaluates the variables as a unified string
value:
isset($_POST['search_term'] . $_POST['postcode']) // Incorrect
While the correct form evaluates them separately as variables:
isset($_POST['search_term'], $_POST['postcode']) // Correct
Use the php's OR (||)
logical operator for php isset()
with multiple operator
e.g
if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {
}
The parameter(s) to isset()
must be a variable reference and not an expression (in your case a concatenation); but you can group multiple conditions together like this:
if (isset($_POST['search_term'], $_POST['postcode'])) {
}
This will return true
only if all arguments to isset()
are set and do not contain null
.
Note that isset($var)
and isset($var) == true
have the same effect, so the latter is somewhat redundant.
Update
The second part of your expression uses empty()
like this:
empty ($_POST['search_term'] . $_POST['postcode']) == false
This is wrong for the same reasons as above. In fact, you don't need empty()
here, because by that time you would have already checked whether the variables are set, so you can shortcut the complete expression like so:
isset($_POST['search_term'], $_POST['postcode']) &&
$_POST['search_term'] &&
$_POST['postcode']
Or using an equivalent expression:
!empty($_POST['search_term']) && !empty($_POST['postcode'])
Final thoughts
You should consider using filter
functions to manage the inputs:
$data = filter_input_array(INPUT_POST, array(
'search_term' => array(
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_NULL_ON_FAILURE,
),
'postcode' => array(
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_NULL_ON_FAILURE,
),
));
if ($data === null || in_array(null, $data, true)) {
// some fields are missing or their values didn't pass the filter
die("You did something naughty");
}
// $data['search_term'] and $data['postcode'] contains the fields you want
Btw, you can customize your filters to check for various parts of the submitted values.