{"id":1792,"date":"2014-01-30T11:14:17","date_gmt":"2014-01-30T10:14:17","guid":{"rendered":"http:\/\/sickel.net\/blogg\/?p=1792"},"modified":"2014-03-17T20:30:37","modified_gmt":"2014-03-17T19:30:37","slug":"simple-ajax-based-autocomplete-in-jquery","status":"publish","type":"post","link":"https:\/\/sickel.net\/blogg\/?p=1792","title":{"rendered":"Simple ajax based autocomplete in jquery"},"content":{"rendered":"<p>Starting to abandon prototype.js to use what seems to be the new standard jquery &#8211; one of the first things I want to do, is to make some autocomplete fields fetching values from a data base.<\/p>\n<p>I have made an input field with the id sampletype. All the examples I found was quite more complicated than what I needed, e.g at <a href=\"http:\/\/jqueryui.com\/autocomplete\/#remote-jsonp\">jqueryui<\/a>. But when I managed to remove all functionallity I don&#8217;t need, then the javascript goes:<\/p>\n<p><code>$(function() {<br \/>\n   url=\"http:\/\/url.to.my.server\/ajaxserver.php\"<br \/>\n    $(\"#sampletype\").autocomplete({<br \/>\n           source: function(request, response) {<br \/>\n            $.ajax({<br \/>\n                url: url,<br \/>\n                data: {<br \/>\n                    fetchnames: \"sampletype\",<br \/>\n                    pattern: request.term<br \/>\n                },<br \/>\n                dataType: 'json',<br \/>\n                success: function(data) {<br \/>\n                    response(data);<br \/>\n                }<br \/>\n            })<br \/>\n        }<br \/>\n    });<br \/>\n});<br \/>\n<\/code><br \/>\nThe fetchnames and pattern parameters are defined by my backend application. The script just fetches all unique names from a table and returns them as a jsonencoded array. The css needs to be fixed a bit to make things look good, I am still not finished there. <\/p>\n<p>The main part of the backend is as follows. This is written for postgres, but most of it should be similar for other databases, e.g. mysql.<\/p>\n<p><code>\/\/ $dbh is set up connected to my server<\/p>\n<p>\/*<br \/>\n   must have done a check that $table really is a valid table, this is a classical possible SQL-injection trap...<br \/>\n   (a prepared sample must know on which table(s) to operate, so this must be build up as a string<\/p>\n<p>  $table - from $_GET['fetchnames']<br \/>\n  $pattern - frin $_GET['pattern']<br \/>\n*\/<\/p>\n<p> $sql=\"select name from $table\";<br \/>\n $sql.=$pattern?\" where lower(name) like lower(:pattern)\":'';<br \/>\n\/*<br \/>\n lower() to make a case insetensive search, may not be needed or be different on other databases<br \/>\n like - to search anywhere within a string, may be different for other databases<br \/>\n*\/<br \/>\n $sql.=\" order by name\";<br \/>\n $sqlh=$dbh->prepare($sql);<br \/>\n if($pattern){<br \/>\n     $pattern=\"%$pattern%\";<br \/>\n     \/\/ searchpattern may be different<br \/>\n     $sqlh->bindParam(':pattern',$pattern);<br \/>\n }<br \/>\n $sqlh->execute();<br \/>\n $data=$sqlh->fetchAll(PDO::FETCH_NUM);<br \/>\n \/*<br \/>\n    $names is a simplified version of $data - as needed in the javascript<br \/>\n *\/<br \/>\n foreach($data as $i){<br \/>\n    $names[]=$i[0];<br \/>\n }<br \/>\n header('Content-type: application\/json');<br \/>\n print(json_encode($names);<\/code><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Starting to abandon prototype.js to use what seems to be the new standard jquery &#8211; one of the first things I want to do, is to make some autocomplete fields fetching values from a data base. I have made an &hellip; <a href=\"https:\/\/sickel.net\/blogg\/?p=1792\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_memberships_contains_paid_content":false,"footnotes":"","jetpack_post_was_ever_published":false},"categories":[4,1],"tags":[],"class_list":["post-1792","post","type-post","status-publish","format-standard","hentry","category-data","category-div"],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/pnVtD-sU","jetpack_sharing_enabled":true,"jetpack_likes_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=\/wp\/v2\/posts\/1792","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=1792"}],"version-history":[{"count":2,"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=\/wp\/v2\/posts\/1792\/revisions"}],"predecessor-version":[{"id":1797,"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=\/wp\/v2\/posts\/1792\/revisions\/1797"}],"wp:attachment":[{"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=1792"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=1792"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickel.net\/blogg\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=1792"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}