ajax

All posts tagged ajax

typeahead

Twitter Typeahead.js has been updated and there are a lot of changes.  I’m going to give a an explanation for a few of their examples and explain the key features and changes that they have made.  For those looking to upgrade to this new version it will require a rewrite of your current Typeahead.js methods so please be aware of that.  The biggest changes are outlined in their changelog.

The most important change in 0.10.0 is that typeahead.js was broken up into 2 individual components: Bloodhound and jQuery#typeahead. Bloodhound is an feature-rich suggestion engine. jQuery#typeahead is a jQuery plugin that turns input controls into typeaheads.

Let’s head to the examples.

The most basic of basic.  Here we have a static list of local data.  Bloodhound needs to be initialized with your data and you can see it handles splitting data up by white space with their tokenizers.  This makes things a lot easier because in previous versions you needed to make sure the tokens to be searched through were already split up by white space.  The Bloodhound object is then initialized and the typeahead object is created.  This is a lot more code but it makes the search more robust as we will see with a more advanced example using prefetch and remote data.

Here we see a very similar example to the one above except that we are getting our data from a URL.  The prefetch variable works to get a set of data and cache it locally.  Even if the page is reloaded that data stays with the user’s browser until it expires or is removed.  As the user begins their search it will have that data ready and on hand but if there is no data to be found in the prefetch Typeahead.js has another URL, stored in the remote variable, that it can make a query to and get data back about what the user is searching for.  These two in conjunction work fantastically well for supplying the user with a set of data that has the speed of being static but can be dynamic by querying the URL for more data as the user goes.  Again we initialize the Bloodhound object and add it to the typeahead initialization.  We are again using the Handlebars template rendering engine to make the search results look great so that hasn’t changed.

The changes are drastic but not hard.  This is a major update to Twitter Typeahead.js and because of that there is deprecation.  My other posts are still useful for older versions but may not apply to versions going forward.  I hope this was helpful in getting you up to speed with the latest version of Twitter Typeahead.js.  If you have any questions or comments feel free to leave them below.

Making jQuery Ajax Requests

ajax

In a lot of my other posts I show sample code that makes heavy use of ajax calls and today I wanted to take a step back and explain what exactly are ajax requests, when you should use them, and how to get the job done.  First, ajax stands for Asynchronous JavaScript and XML which may still be a bit too technical but essentially what it does is allow you to make a request to the server for data without having to refresh the page.  Obviously this is a very useful tool to have no matter what you are doing on the web.  No one likes to have to wait for the entire page to reload all of the images and content just because you clicked a button to show more data on a section of the page.

Ajax calls should be used anywhere you want to get data without doing a hard refresh.  This can range from something small like updating a table every ten seconds automatically or to something complicated like automatic submission and verification of individual form fields.  One way to leverage the asynchronous nature of these calls is to load your main html page that merely holds placeholder divs with no content in them.  Once that very light page is loaded you make a series of ajax requests to the server to fill in those various portions of the page.  This gives the user a very quick response time so they see that your site is up and running and other, more intensive, portions of the site can be loaded when they get processed.  Ever gone to a site and after the page has loaded there is still a spinning wheel on some section of the page?  That’s an ajax call running and they have let you know something will be there soon.

To make an ajax call using jQuery requires very little code but you need to understand the back and forth interaction to make sure you use and display the data correctly.  An ajax call consists of the method call and a dictionary of parameters to be used.  There are many optional ones but I will go over the more commonly used ones.

In the example above we are submitting a form and then adding the returned html data to the table.  This allows us to dynamically add to an HTML table without needing to refresh the page every time.  Let’s go through each of the parameters in the dictionary that is passed with the ajax request.

  • URL – This is obviously the URL where the request is going to be made.  It can be relative, as it is in this example, or an explicit URL like http://www.google.com/.
  • TYPE – How the request is being sent.  Generally speaking a GET request is used when you are reading from the database and requesting information and a POST request is one in which you are doing a write or update to the database.  In our case here we are adding a post so that would fall under the write category and we do a POST.
  • DATA – The parameters that are going to be held in the request.  This includes all of your fields in your form, which is what I’m doing in the example above, or any GET parameters if you use type GET.  The .serialize() command will take all of your named fields in a form and put them in a dictionary to pass in an ajax request.
  • ERROR – If the server responds with an error code of any kind this is what will be triggered.  The data variable that is passed to the error function contains all of the data sent back from the server.
  • SUCCESS – When the server responds with a 200 code, a success, this will be triggered.

You’ll notice that the error and success sections are functions that use a data variable.  That data variable is what is sent back from the server.  It can be anything you’d like it to be.  In the example above the server is sending back pure HTML.  If you want to use other things like lists and dictionaries you’ll need to specify another parameter called dataType and set it to JSON.  Then have your server send back a JSON string and you’ll be all set.  Because they are functions you can really do whatever you’d like at the point of return.

Ajax calls are crazy powerful and unbelievably useful for nearly aspect of web development.  Play around with it and make your websites better.  There are a lot of ajax parameters you can use with your jQuery call.  I only touched on a few of the more important ones here.

typeaheadjs

 

New Version – Twitter Typehead.js v0.10

Bootstrap dropped support for their bootstrap-typeahead.js and suggested we all use Twitter’s Typeahead.js.  This was a pretty big change for us and we encountered a bit of a learning curve because the documentation wasn’t exactly what we had hoped it would be.  Typeahead.js is incredible and can do some amazing things though and we are happy to be using it.

The first issue is that right out of the box it will not work with Bootstrap 3.  Support is still being looked at but in the mean time there are some fixes.  Here is a thread about the issue on their GitHub page with some helpful people posting solutions for the interim.  Below is the code we are using for ours which I’m sure will change in the coming days.

Once we got the formatting and could create our typeahead inputs we needed data for them.  We were using AJAX calls to our server to get the list as the user typed.  This worked but was a little slow.  Typeahead now has a few different ways of populating data into the input field.

Local

Local is a list of hard coded values right in your JavaScript

Prefetch

When the page is loaded the ajax call is made and stored in the browser’s local storage so the next time you visit the page it does not need to make another request unless the time-to-live has expired.  The ttl is defaulted to one day but you can change that in the options you pass.  One thing to note is that your browser has a limited amount of storage for this type of thing.  When we tried to pull our contacts list all in one go it would crash typeahead because the browser ran out of memory for local storage.  Our fix for this was that the prefetch URL would only return a limited number of entries, for example, the last 1000 updated contacts.

Remote

If the user starts to try and type something that isn’t immediately available through prefetch or local it falls back to your remote URL.  Just place the %QUERY tag in your URL and it will take what the user has entered and make a call to your server for a list using that query.

Full Example:

Templates

Typeahead supports your own custom templates for the drop down.  In our case we are just making the customer number bold and displaying their name but you could do everything from changing fonts, making inline lists, or even displaying images inline with your results.  Very cool.

Datums

We learned the hard way about a few different things when formatting results for your typeahead.  Typeahead expects a list of dictionaries with certain values, these are called datums.  Only two keys are required by typeahead, value and tokens.  After that you can add your own keys to be used by the typeahead for whatever purpose you’d like, whether it’s changing what happens on click or an image to be placed inline.  The value is the actual value of the typeahead, what the user is trying to get to.  Tokens are a list of strings that help the user get to where they want to go.  One very important note, the tokens must be single word strings — no spaces.   Spaces come across as %20 and when the user enters a normal space the typeahead doesn’t recognize that correctly.  So what we did was split the name of the company/contact into a list of separate strings for each word and that worked great.

Onward

Still playing around with it but I feel like we have a pretty good grasp on it.  Here is a list of their examples just to help drive the point home a bit further. Just waiting on the Bootstrap 3 support but overall we are happy with the new typeahead after we spent a long time trying to figure out all of the quirks we were having with it.

Hope this is helpful to others out there.

EDIT 16 September 2013

Some people were complaining about the dropdown not dynamically scaling.  Git user karimlahlou has posted this to fix that problem.

Thank you @ashleydw, finally i got it working. for those need to adjust the list width, use this function:

Hope this helps a few people.