Search in WordPress is complicated matter because:
- WP doesn’t do it very well out of the box
- People tend to have varied expectations of how precisely search should work
- Even light (from human perspective) requirements for search tend to translate in complicated and involved code
Building search from scratch is involved (I know because I did exactly that for a while for clients) and you should totally look for search plugins or other compromise (like search as service) first.
To briefly enumerate specific issues with your code:
- custom Ajax endpoints generally should not be used, see AJAX in Plugins
- using raw MySQL function to query almost never used, see wpdb (and especially parts about securing your queries against injections)
query_posts()
should not be used, see When should you use WP_Query vs query_posts() vs get_posts()?