Reputation: 311
I am new to AJAX, and I stumbled upon a small problem. I have a custom search field for pages within my database:
PHP:
if(isset($_GET['fdf_search'])){
$term_search = $_GET['fdf_search'];
$fdf_pages = $mysqli_con->select("SELECT * FROM `pages` WHERE `alias` LIKE '%".$term_search."%'");
}
AJAX:
$(document).ready(function() {
$("#fdf-search").keyup(function() {
// Assign $_GET['fdf-search'] to variable "searchKey" in js
var searchKey = $('#fdf-search').val();
if (searchKey == "") {
//nothing
}else{
console.log('ajax called');
$.ajax({
type: "GET",
url: "/fluidify/fdf-admin/functions/fdf_system_search.php",
data: {
search:searchKey
},
success: function(html){
window.history.replaceState(null, null, "?fdf_search=" + searchKey + "");
}
});
}
});
});
HTML:
<form action="" method="get">
<input id="fdf-search" class="fdf-search" type="text" placeholder="zoeken" name="fdf_search" value="">
<input class="fdf-search" type="submit" value="Zoeken" name="fdf_submit_search">
</form>
When I type in any word, I want my AJAX to trigger the PHP query and find and return any result. Right now window.history.replaceState(null, null, "?fdf_search=" + searchKey + "");
is changing the GET
in my URL, but for some reason it does nothing.
All help is appreciated :)
EDIT: select(); class
public function select($query,$report = NULL){
$result_array = array();
$result_empty = false;
$result = $this -> query($query);
if($result !== false){
while($row = $result -> fetch_assoc()){
$result_array[] = $row;
}
return($result -> num_rows === 0) ? false : $result_array;
}else{
if($report === true){
echo "error in query:";
print_r($result);
print_r($result_array);
print_r($query);
echo "<br>";
}
}
}
Upvotes: 1
Views: 62
Reputation: 826
To get results back you should output something from your php code like so :
if(isset($_GET['fdf_search'])) {
$term_search = $_GET['fdf_search'];
$fdf_pages = $mysqli_con->select("SELECT * FROM `pages` WHERE `alias` LIKE '%".$term_search."%'");
//output the result
echo json_encode($fdf_pages);
}
and your ajax call should look like this:
$.ajax({
type: "GET",
url: "/fluidify/fdf-admin/functions/fdf_system_search.php?fdf_search=" + searchKey
}).done(function(json){
//parse the ajax response
search_result = JSON.parse(json);
//do something with search_result ...
});
Upvotes: 1