var searchUser = function(searchQuery){
    var request = $.ajax({
        type: "POST",
        data: { search:searchQuery},
        success: function(reply){
            $("#search-box").css("display", "block");

I know this is a terrible way of doing it, right? How else would I best go about outputting the search result to my #search-box? Right now, I send an AJAX request to my search.php file which returns all the HTML of the search. Surely this wouldn't be good from a performance perspective?


1 Answer 1

  • 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) {
        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>";
        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");
  • \$\begingroup\$ Thank you very much for my insight. I have done everything (bar the JSON but which Il do later) you said and its now looking a lot better. \$\endgroup\$
    – DribbleUI
    Jul 29, 2014 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.