I want to get a value from the user using the following input field:
<div class="search">
<span class="text">یک کاربر برای شروع چت انتخاب کنید</span>
<input type="text" class="active" placeholder="یک نام برای شروع چت وارد کنید">
<button class="active"><i class="fas fa-search"></i></button>
</div>
Then, on the JavaScript page, save the value of this field in a variable:
const searchBar = document.querySelector(".users .search input")
Then I send that variable to another PHP page by Ajax:
searchBar.onkeyup = () =>{
let searchTerm = searchBar;
if(searchTerm.Value != ""){
searchBar.classList.add("active");
}else{
searchBar.classList.remove("active");
}
let xhr = new XMLHttpRequest();//creating xml object
xhr.open("POST","php/search.php",true);
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
usersList.innerHTML = data;
}
}
}
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("searchTerm=" + searchTerm);
}
setInterval(() => {
//start ajax
let xhr = new XMLHttpRequest();//creating xml object
xhr.open("GET","php/users.php",true);//as we have get data, we use GET, not POST
xhr.onload = () => {
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
if(!searchBar.classList.contains("active")){
usersList.innerHTML = data;
}
}
}
}
xhr.send();
}, 500);// this function will run frequently after 500ms
Then I want to receive the variable sent by Ajax on this PHP page and use it to read the information I want from the database:
<?php
$searchTerm="";
$output = "";
if(isset($_POST["searchTerm"])){
$searchTerm = test_input($_POST["searchTerm"]);}
function test_input($data){
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;}
try{
class TableRows extends RecursiveArrayIterator{
function __construct($array = [], $flags = 0){
parent::__construct($array,$flags);
}
function current(): mixed{
return parent::current();
}
}
$STMT = $conn->prepare("SELECT * from users WHERE fname LIKE '%$searchTerm%' OR lname LIKE
'%$searchTerm%'");
$STMT->execute();
$result = $STMT->setFetchMode(PDO::FETCH_ASSOC);
foreach(new RecursiveArrayIterator($STMT->fetchAll()) as $k => $v){
$output .= '<a href="chat.php?user_id='.$v['unique_id'].'">
<div class="content">
<img src="php/uploads/'. $v['img'] .'" alt="">
<div class="details">
<span>'. $v['fname'] . " " . $v['lname'] .'</span>
<p>این یک پیام امتحانی است</p>
</div>
</div>
<div class="status-dot"><i class="fas fa-circle"></i></div>
</a>';}
}catch(PDOException $e){$e->getMessage();}
$conn = null;
echo $output;
?>
But no value is sent to the last PHP page to search from the database and I don’t know why.
New contributor
Ahmad Banaeyan is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.