I want to implement a small user autosearch feature for private messages. I cannot find the reason why the below code is not working. JS Ajax ends up each time in .fail node despite the fact that there is a user in DB that e.g. starts with "m".
js:
$($userSearchForm).on('keyup', function () {
var $query = $('#userSearch').val();
$
.ajax({
url: '../../../rest/restEndPoints/Privatemessage.php',
type: 'POST',
data: $query
})
.done(function (response) {
console.log(response);
})
.fail(function (error) {
console.log('Username not found', error);
});
});
Privatemessage.php REST endpoint:
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST["userSearchForm"])) {
$query = $_POST["userSearch"];
$queryResult = Privatemessage::searchByUsername($conn, $query);
$response = ['success' => $queryResult];
}
class Privatemessage
static public function searchByUsername(PDO $pdo, $userName) {
$stmt = $pdo->prepare("SELECT u.username FROM Users u WHERE userName LIKE CONCAT('%',:userName,'%')");
$result = $stmt->execute([
'userName' => $userName
]);
$ret = [];
if ($result === true && $stmt->rowCount() > 0) {
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$loadedUsername = new Privatemessage($pdo);
$loadedUsername->userName = $row['username'];
$ret[] = $loadedUsername;
}
return $ret;
}
return null;
}
HTML on privateMessage.php subpage:
<form class="form-user-search" id="userSearchForm" action="" method="post">
<div class="form-group">
<label for="userSearch">Find user</label>
<input name="userSearch" id="userSearch" class="form-control" placeholder="Find user" autofocus>
<input name="newPrvMessage" id="newPrvMessage" class="form-control" placeholder="Type in message" autofocus>
<div id="userSearch" style="display:none;"></div>
<button class="btn btn-default btn-block" type="submit" id="userSearchButton">Submit new private message</button>
</div>
</form>
For some reason, when I look up the request that's being sent, the response is only the below:
Despite "not finding" Class, subpage still pulls correctly messages that have been sent/received (rest.php file includes .php classes / endpoints dynamically, depending on subpage you enter via navbar)