I'm trying to do some simple AJAX searching with jQuery and PHP. However I can't seem to get the proper search string to work. I want to search by title, and if the title hasn't seen set, just display all results when clicking search. Also I would like to show the results as beautiful HTML and not returned back in JSON-like-code. Somthing like:
$book["title"]
$book["author"]
$book["description"]
SQL Set-up:
Table Name: books Table Fields: id, title, author, description
HTML:
<div id="search">
<form action="#">
<p><label for="title">Book Title:</label> <input type="text" id="search_title" name="search_title"></p>
<p><input type="submit" id="search_submit" name="search_submit" value="Search!"></p>
<p><em><small>For example A Game of Thrones or The Lord of the Rings</small></em></p>
<hr>
</form>
</div>
<div id="search_results">
</div>
<script>
$(document).ready(function() {
$("#search_submit").on("click", function() {
var searchTitle = $("#search_title").val(),
data = 'title=' + searchTitle;
if(searchTitle) {
$.ajax({
type: "POST",
url: "getBooks.php",
data: data,
success: function(res)
{
$("#search_results").html(res);
}
});
}
return false;
});
});
</script>
PHP:
if(isset($_GET["title"])) {
$title = $_GET["title"];
}
if(isset($title) && !empty($title)) {
$pdo_title = "WHERE title LIKE '%" . $title . "%'";
} else {
$pdo_title = "";
}
$pdo_books = "books";
$pdo = new PDO("mysql:dbname=removed;host=removed","removed","removed");
$statement = $pdo->prepare("SELECT * FROM $pdo_books $pdo_title");
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo $json;