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;
If its about formatting output in HTML from JSON, Then in your jQuery code you would need to parse json and repeat loop for each json objects in an array and add HTML to your page dynamically.
if(searchTitle) {
$.ajax({
type: "POST",
url: "getBooks.php",
data: data,
success: function(res)
{
var my_table="<table>";
$.each(res, function(i, obj){
my_table+="<tr> <td> "+obj.clumn_name+" </td> <td> "+obj.clumn_name2+" </td> </tr> ";
});
my_table+"</table>";
$("#search_results").html(my_table);
}
});
}
You have mentioned the method as post in ajax and you are trying with $title = $_GET["title"];
Try using
$title = $_POST["title"];
if(isset($_POST["title"])) {
$title = $_POST["title"];
}