Wednesday, 9 March 2011

Using jQuery to perform a Bing API search - explained.....

After a recent discussion, I was asked to explain how the jQuery Bing API search found on the site worked , so decided, if its useful to one, it maybe useful to others, so in this post I will explain line by line what's happening.

Below is an example of what you will get if you used to code (except I've added a button to clear the results), all you need to do is type! This kind of search box does have one major downside, if the user has javascript turned off, it won't work!! But for majority of users out there it will 

The Example:
Search For:

The basics of the search are:
  1. An input box for your user to type what they are searching for.
  2. A container to show off the results that get returned.
  3. Some jQuery to perform the magic for you.
    1. NOTE: You will need to get an API ID from Bing to allow you to perform searches on your own site. You can get one here.
Lets see some code then:
The input box - straight forward enough:
<input type="text" class="search_input" />

NOTE: in jQuery if you want to reference a DOM element, if it has an ID attribute use #idName, if you want to reference an element by its class name use .className

The results box - again straight forward enough:
<div id="result"></div>

Finally the jQuery magic:
1. $(document).ready(function(){
2.  $(".search_input").focus();
3.  $(".search_input").keyup(function() {
4.   var search_input = $(this).val();
5.   var keyword = encodeURIComponent(search_input);
6.   var appID = "YOUR-OWN-APP-ID-FROM-BING";
7.   var yt_url=''+appID+'&query='+keyword+'&sources=web'; 
8.   $.ajax({
9.    type: "GET",
10.    url: yt_url,
11.    dataType:"jsonp",
12.    success: function(response){
13.     $("#result").html('');
14.     if(response.SearchResponse.Web.Results.length){
15.      $.each(response.SearchResponse.Web.Results, function(i,data){
16.       var title=data.Title;
17.       var dis=data.Description;
18.       var url=data.Url;
19.       var final="<div class="webresult"><div class="title"><a href="">"+title+"</a></div><div class="desc">"+dis+"</div><div class="url">"+url+"</div></div>";
20.       $("#result").append(final);
21.      });
22.     }
23.     else {
24.      $("#result").html("<div id="no">No results</div>");
25.     }
26.    }
27.   });
28.  });
29. }); 

OK let's break it down now......

  1. When the page has finished loading, run the following code.
  2. Focus the user on the input box so they can start typing straight away.
  3. Bind a function onto the input box, listening for a keypress.
  4. Store whats been written in the input box as a variable.
  5. Encode what was in the input box so it can be passed in a URL to Bing.
  6. Store your Bing application ID you got earlier on into a variable.
  7. Store the URL to query as a variable. To break this down a little, we are passing our application ID, the value from the input box and also informing Bing we want results from the web.
  8. Start a jQuery Ajax request.
  9. Set the ajax type to a GET request.
  10. Set the URL for the ajax call to contact.
  11. Set the data type as jsonp (a cross browser request for JSON formated results)
  12. If the ajax request was successful, perform the following (data that was returned will be available as response).
  13. Clear any previous results.
  14. Check we actually got some results (If there were none, the length would be 0 - 0 is equal to false. When queried like this, anything other than 0 is true)
  15. Now use the jQuery .each() function to loop through each result which was returned, performing the following for each result.
  16. Store this results title as a variable.
  17. Store this results description as a variable.
  18. Store this results URL as a variable.
  19. Store a HTML snippet to display this result, putting each part into a container (this allows our CSS to make the results look pretty).
  20. Use jQuery's .append() method to add the HTML snippet to the end of the results container.
  21. Finished looping through the results.
  22. Finished what happens if there were results.
  23. Perform the following in the case no results were returned.
  24. Use jQuerys .html() method to set the results container to show a message saying nothing came back. This method would clear everything else from the container leaving just what it sets.
  25. Finished what happens if nothing was returned.
  26. Finished what to do when the ajax is successful.
  27. Finished the ajax call.
  28. Finished what to do when a key is pressed on the input box.
  29. Finished what to do when the page has finished loading.
The final, but optional part for this, by now, rather long post is the CSS to style the results. I won't break this lot down, there is plenty of guides out there which will help you understand CSS if you need to know:

.title a{

.title a:hover{



 border-bottom:1px dashed #dedede

#result {
 text-align: left;
 font-family: arial,helvetica,sans serif;

One final note:
The above code is what I was asked to explain, it isn't in my opinion a fully polished example I would put into production. When I have a moment, I will polish up the jQuery code a little so it gives somewhat of a nicer user experience - i.e. advising the user when the ajax fails, and performing just one request instead of one for every letter pressed (see the post for why this can be a problem).


Some jQuery books from

HTML5: Up and Running     HTML5 and CSS3: Develop with Tomorrow's Standards Today (Pragmatic Programmers)     jQuery Cookbook: Solutions & Examples for jQuery Developers (Animal Guide)

No comments:

Scroll to Top