jQuery UI - autocomplete from a database - javascript

What are the steps for having jQuery UI's autocomplete use a database?
Specifically, how do I pass this script the entered value? How does autocomplete receive the script's json?
What I know:
1) Change the 'source option' to a script that queries the database.
2) ?
Current code:
$("#searchInput input").autocomplete({
source: "script_that_queries_the_db.php"
});

step 2? Have your php page mysql_query based on $_GET['term'] and return the results using json_encode.
Edit: Also, make sure the array you pass to json_encode is a flat array, otherwise jQueryUI won't read it as well as we'd like without writing more custom code.

The simplest way is to have your server return the results in json. See this example:
http://jqueryui.com/demos/autocomplete/#remote
Another way to do it is to make the request and parse the response yourself, by passing a function as source. See this example:
http://jqueryui.com/demos/autocomplete/#remote-with-cache
In either case the data passed to autocomplete must be an array of objects each with a label and a value.

Related

Passing php array to javascript function from external php file

I'm working on autofilling an html form based on data from a sqlite database.
I'm using a modified version of the code from this site and in its basic feature it works as expected.
The main input element calls, "onkeyup", a javascript function called "lookup", that in turn calls a external php script passing the current string to query the database.
The script returns a string to update the input form:
echo '<li onClick="fill(\''.$result->value.'\');">'.$result->value.'</li>';
The javascript function "fill" is as follows:
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
"#inputstring" is simply an input element.
What I would like to do instead of returning a string is to return an array and parse it inside the "fill" function to assign the different values to different elements in html.
The problem is that to pass the php array to javascript I have to convert it somehow. I've tried to make it a json string as suggested many times here on stack, but for what I suppose is a problem of quotes, it always return a null value.
I've tried:
$valuetopass = json_encode($query_result);
whithout
echo '<li onClick="fill('.$valuetopass.');">'.$query_result['text'].'</li>';
and with quotes
echo ''.$query_result['text'].'';
And both fail.
I'm aware that similar question have been already asked 1, 2,ecc... But all of the answers suggest to embed php when assigning the javascript variable. In my case the php is called from the function "lookup" and from that php script I want to return to the function "fill".
How can I produce from inside php a string that includes a json string with a format that can be passed to the "fill" function?
Or alternatively how can I rework the problem so that I don't need to do it at all?
Your JSON string is likely to contain ", so of course you get a syntax problem when you insert that into onClick="fill(...);" untreated.
Using PHP’s htmlspecialchars should be able to fix this in this instance.
In the long term, you might want to look more into the separation of code and data though.
Attaching event handlers using inline HTML attributes is kinda “old-school”, today that should rather be done from inside the script, using addEventListener resp. whatever wrapper methods a JS framework might provide for that. The JSON data could then for example be put into a custom data attribute, so that the script can read the data from there.

supplying initialization json string as parameter to jquery method

i have just begun using jquery datatables in my project and I do like it so far. I have many tables, sometimes 2-3 on a page. Rather than have to keep track of what initialization string I am using for a specific table and trying to remember what webpage its on, I have built an xml file to store all the initialization strings. I built some jquery functions to retrieve the strings on document ready but it never dawned on me how to actually inject the json into the method as a parameter.
If i was doing it manually you would call
selector.dataTables(json initializer string here);
Once I have that string how do I actually inject it into the method call? Or do I have to create that whole code line and inject it into my script?
If the json data comes in as something like this:
{"order": [[ 3, "desc" ]]}
You could use jquery to get the JSON via a HTTP GET request.
$.getJSON('somejson.json',function(data){
someSelector.dataTables(data)
});
Because you are using getJSON it will expect the JSON to be in that format and do the parsing for you.
Or if the JSON is available already(since you are using jquery you can use it to parse the JSON data just in case there may be a browser support issue since IE7 and below does not support JSON.parse.):
var options = $.parseJSON(someData);
someSelector.dataTables(options)
you can assign the json string to a variable...
var tableSettings = theJsonString;
selector.dataTables(tableSettings);
you may need to convert the string to an object first...
//javascript
var tableSettings = JSON.parse(theJsonString);
//jquery
var tableSettings = $.parseJSON(theJsonString);

jQuery AutoComplete Fill Array

I'm attempting to use jQuery's autocomplete feature, and after reading several posts I still have two questions:
1) I've gotten autocomplete to work with the code posted at the bottom, however I need the array titled "data" to be filled from our database. I've been trying to use different methods to fill this via AJAX. I tried using $.get and $.ajax. What is the correct syntax to accomplish this?
2) This array will be big, I will have 60,000 plus values if I just fill the array once. I was wondering if it's possible to perform an AJAX request to fill the array every-time the user enters a new letter? Is this better to do, or just fill the array with all values at once? By better, which taxes the system less?
//This code works
<script type="text/javascript">
$(document).ready(function(){
var data = "Facebook Gowalla Foursquare".split(" ");
$("#search_company").autocomplete(data);
});
</script>
//display company live search
echo('<form id="form" method="post" action="competitor_unlink.php" onsubmit="return">');
echo('Company: <input id="search_company"/>');
echo('<br/>');
echo('<button type="submit" value="Submit">Submit</button>');
echo('</form>');
Look at this demo - it's what you want to do (get data using ajax):
http://jqueryui.com/demos/autocomplete/#remote
You can pull data in from a local
and/or a remote source: Local is good
for small data sets (like an address
book with 50 entries), remote is
necessary for big data sets, like a
database with hundreds or millions of
entries to select from.
Autocomplete can be customized to work
with various data sources, by just
specifying the source option. A data
source can be:
an Array with local data a String,
specifying a URL a Callback The local
data can be a simple Array of Strings,
or it contains Objects for each item
in the array, with either a label or
value property or both. The label
property is displayed in the
suggestion menu. The value will be
inserted into the input element after
the user selected something from the
menu. If just one property is
specified, it will be used for both,
eg. if you provide only
value-properties, the value will also
be used as the label.
When a String is used, the
Autocomplete plugin expects that
string to point to a URL resource that
will return JSON data. It can be on
the same host or on a different one
(must provide JSONP). The request
parameter "term" gets added to that
URL. The data itself can be in the
same format as the local data
described above.
The third variation, the callback,
provides the most flexibility, and can
be used to connect any data source to
Autocomplete. The callback gets two
arguments:
1) A request object, with a single
property called "term", which refers
to the value currently in the text
input. For example, when the user
entered "new yo" in a city field, the
Autocomplete term will equal "new yo".
2) A response callback, which expects
a single argument to contain the data
to suggest to the user. This data
should be filtered based on the
provided term, and can be in any of
the formats described above for simple
local data (String-Array or
Object-Array with label/value/both
properties). It's important when
providing a custom source callback to
handle errors during the request. You
must always call the response callback
even if you encounter an error. This
ensures that the widget always has the
correct state.
Here's an example of how to specify a URL that will return the results from the database as JSON using the jQuery UI autocomplete plugin.
$("#search_company").autocomplete({
source: "/Search", // <-- URL of the page you want to do the processing server-side
minLength: 4 // <-- don't try to run the search until the user enters at least 4 chars
});
Autocomplete will automatically append a querystring parameter named "term" to the URL so your search page will need to expect that. Not sure what server technology you're using but since I'm a .NET developer here's an example in ASP.NET MVC :)
public ActionResult Search(string term) {
var results = db.Search(term); // <-- this is where you query your DB
var jqItems = new List<jQueryUIAutoCompleteItem>();
foreach (var item in results) {
jqItems.Add(new jQueryUIAutoCompleteItem() {
value = item.CompanyId.ToString(),
id = item.CompanyId.ToString(),
label = item.CompanyName
});
}
return Json(jqItems.ToArray(), JsonRequestBehavior.AllowGet);
}
jQueryUIAutoCompleteItem is just a data container that represents the JSON format that the autocomplete plugin expects.
public class jQueryUIAutoCompleteItem {
public string value { get; set; }
public string label { get; set; }
public string id { get; set; }
}
You're correct that sending the whole 60,000-record list to the client's machine doesn't sound like the best solution. You'll notice that Google only shows you a handful of the most popular matches in its autocomplete, as to many other websites.
You could shorten the list by waiting for the user to type two or three letters instead of searching on the first one.
You could do page chunking in the list (it goes by various names). That is, only return the top 10 or 15 matches. The user can get more of the list by scrolling or by clicking on a "Show More Results" link. You have to write (or search for) all the javascript code for this, of course.
It might be a bit late to this post but for others that find it. I created a plugin for jquery and the jqueryui autocomplete control that works with Foursquare. You can read the post and download the plugin at Foursquare Autocomplete Plugin

How do I remove the square brackets at the end of a JS variable name during AJAX calls?

I currently have the following javascript array:
var stuffs = ['a', 'b'];
I pass the above to the server code using jQuery's load:
var data = {
'stuffs': stuffs
};
$(".output").load("/my-server-code/", data, function() {
});
On the server side, if I print the content of request.POST(I'm currently using Django), I get:
'stuffs[]': [u'a', u'b']
Notice the [] at the prefix of the variable name stuffs. Is there a way to remove that [] before it reaches the server code?
This is default behavior in jQuery 1.4+...if you want the post to be &stuffs=a&stuffs=b instead of &stuffs[]=a&stuffs[]=b you should set the traditional option to true, like this:
$.ajaxSetup({traditional: true});
Note this affects all requests... which is usually what you want in this case. If you want it to be per-request you should use the longer $.ajax() call and set traditional: true there. You can find more info about traditional in the $.param() documentation.
When an array is submitted using a GET request, through a form or AJAX, each element is given the name of the array, followed by a pair of optionally empty square brackets. So the jQuery is generating the url http://example.com/get.php?stuff[]=a&stuff[]=b. This is the only way of submitting an array, and the javascript is following the standard.
POST requests work in exactly the same way (unless the json is sent as one long json string).
In PHP, this is parsed back into the original array, so although the query string can be a little strange, the data is recieved as it was sent. $_GET['stuff'][0] works correctly in PHP.
I'm not sure how Django parses query strings.
The [] indicates that the variable is an array. I imagine that the appending of the [] to your variable name is Python/Django's way of telling you it is an array. You could probably implement your own print function which does not show them.

JavaScript array to ColdFusion

I have an array I've created in JavaScript. The end result comes out to element1,element2,,,element5,element6,,,element9.... etc
Once passed to ColdFusion, it removes the null elements, I end up with element1,element2,element5,element6,element9
I need to maintain these spaces, any ideas? My problem may begin before this, to explain in more detail...
I have a form with 13 elements that are acting as a search/filter type function. I want to "post" with AJAX, in essence, i'm using a button to call a jQuery function and want to pass the fields to a ColdFusion page, then have the results passed back. The JavaScript array may not even be my best option.
Any ideas?
Are you deserializing the jS array into a list? CF ignores empty list fields using its built-in functions. This can be worked around by processing the text directly. Someone has already done this for you, fortunately. There are several functions at cflib.org, like:
ListFix
ListLenIncNulls
etc, etc, etc.
In exchanging data between javascript and coldfusion have a look at using JSON.
http://www.json.org
http://www.epiphantastic.com/cfjson/
Instead of using the CF ListToArray function, use the Java String methods to split the string into an array. This will maintain the empty list items.
<cfset jsList = "item1,item2,,item4,item5,,item6">
<cfset jsArray = jsList.split(",")>
<cfdump var="#jsArray#">
you are using array in JavaScript,Fine. instead of assigning by default empty value,assign some dummy value. whenever you use this array value ignore dummy value using condition.

Categories