- You should ensure your spacing is consistent.
- Since you're using a function expression rather than a declaration, you should terminate the line with a semicolon.
- You aren't making any use of the
request
variable, so why even declare it?
- You aren't taking advantage of method chaining. This is causing you to construct two jQuery objects for
#search-box
when you only need one.
- You're right in that this is not the best way to handle it; consider returning JSON or XML.
- You have a
success
callback but not an error
callback. In this particular case I don't imagine it would be too bad (your search box will just remain hidden, presumably), but you may want to add one anyway.
Here's how I think your code could look.
var searchUser = function(searchQuery) {
$.ajax({
url: "search.php",
type: "POST",
data: { search: searchQuery },
dataType: "json",
success: function(response) {
var resultList = response.reduce(function(accumulator, value) {
return accumulator + "<li>" + value + "</li>";
}, "<ul>");
/* alternative for older browsers:
var resultList = "<ul>";
$.each(response, function(index, element) {
resultList += "<li>" + element + "</li>";
});
*/
resultList += "</ul>";
$("#search-box").html(resultList).show();
},
error: function() {
$("#search-box").html("An error occurred. Search suggestions could not be loaded.");
}
});
};
search.php
would then have to do something like:
$results = array("suggest", "suggestion", "suggested", "suggesting");
die(json_encode($results));