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

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?

\$\endgroup\$
3
\$\begingroup\$
  • 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));
| improve this answer | |
\$\endgroup\$
  • \$\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 '14 at 21:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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