I want to create a live search box in my html project. The user will use an input box and typing the email he gets the results when the user is found in the database or not. Depending of the result, the PHP will send an array of data back to JQery so I can update my front-end.
Unfortunately, I have problems passing the data from JQuery to PHP. I tried many methods from the web, and I can't understand why I can not accomplish what I want.
Here's my code:
HTML
<div id="person-search">
<form >
<label class="person-search-label">Insert Person's Id</label>
<input type="email" class="person-search-input" onkeyup="ShowSearchResult(this.value)">
</form>
<div class="search-person-res">
<label id="Label-Result"></label>
<div style="padding-top: 5px;" id="UserNameSearchResult"></div>
</div>
</div>
JS
function ShowSearchResult(value) {
$.post("lib/search.php", {name:value},function(data){
document.getElementById('Label-Result').innerHTML = data[0];
if (data[1] != null) {
document.getElementById('UserNameSearchResult').innerHTML = data[1];
var addBtn = "<form method=\"post\"><button class=\"add-new-person\" type=\"submit\">Add the person</button></form>";
$( addBtn ).insertAfter( $( "#UserNameSearchResult" ) );
}
});
}
PHP
<?php
session_start();
define("DB_HOST", '');
define("DB_USER", '');
define("DB_PASSWORD", '');
define("DB_DATABSE", '');
$conn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysql_select_db(DB_DATABSE, $conn);
$search = $_POST["name"];
$sq = mysql_query("SELECT * FROM Users WHERE UserEmail = '%{$search}%'");
$UserInfo = mysql_fetch_row($sq);
if ($UserInfo) {
$data = array('We found results', $UserInfo[2]);
echo json_encode($data);
}
else {
$data = array('We couldn\'t found results', null);
echo json_encode($data);
}
?>