BING Search using ASP.NET and jQuery Ajax

Posted by hajan on ASP.net Weblogs See other posts from ASP.net Weblogs or by hajan
Published on Mon, 07 Mar 2011 01:02:00 GMT Indexed on 2011/03/07 8:10 UTC
Read the original article Hit count: 533

Filed under:
|
|
|
|

The BING API provides extremely simple way to make search queries using BING. It provides nice way to get the search results as XML or JSON. In this blog post I will show one simple example on how to query BING and get the results as JSON in an ASP.NET website with help of jQuery’s getJSON ajax method.

Basically we submit an HTTP GET request with the AppID which you can get in the BING Developer Center.

To create new AppID, click here.

Once you fill the form, submit it and you will get your AppID.

Now, lets make this work in several steps.

1. Open VS.NET or Visual Web Developer.NET, create new sample project (or use existing one) and create new ASPX Web Form with name of your choice.

2. Add the following ASPX in your page body

<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="txtSearch" runat="server" /> <asp:Button ID="btnSearch" runat="server" Text="BING Search" />
    <div id="result">
    
    </div>
    </form>
</body>

We have text box for search, button for firing the search event and div where we will place the results.

3. Next, I have created simple CSS style for the search result:

<style type="text/css">        
    .item { width:600px; padding-top:10px; }        
    .title { background-color:#4196CE; color:White; font-size:18px;
             font-family:Calibri, Verdana, Tahoma, Sans-Serif; padding:2px 2px 2px 2px; }
    .title a { text-decoration:none; color:white}
    .date { font-style:italic; font-size:10px; font-family:Verdana, Arial, Sans-Serif;}        
    .description { font-family:Verdana, Arial, Sans-Serif; padding:2px 2px 2px 2px; font-size:12px; }
    .url { font-size: 10px; font-style:italic; font-weight:bold; color:Gray;}
    .url a { text-decoration:none; color:gray;}
    #txtSearch { width:450px; border:2px solid #4196CE; }
</style>

4. The needed jQuery Scripts (v1.4.4 core jQuery and jQuery template plugin)

<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.4.min.js" type="text/javascript"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>

Note: I use jQuery Templates plugin in order to avoid foreach loop in the jQuery callback function. JQuery Templates also simplifies the code and allows us to create nice template for the end result. You can read more about jQuery Templates here.

5. Now, lets create another script tag where we will write our BING search script

<script language="javascript" type="text/javascript">
    $(document).ready(function () {
        var bingAPIKey = "<Your-BING-AppID-KEY-HERE>";
        
        //the rest of the script goes here
        
    });
</script>

6. Before we do any searching, we need to take a look at the search URL that we will call from our Ajax function

BING Search URL : http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&AppId={appId}&query={query}&sources={sourceType}

The URL in our example is as follows:

http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid=" + bingAPIKey + "&query=" + keyWords + "&sources=web

Lets split it up with brief explanation on each part of the URL

  • http://api.search.live.net/json.aspx – is the main part of the URL which is used to call when we need to retrieve json result set.
  • JsonType=callback&JsonCallback=? – using JsonType, we can control the format of the response. For more info about this, refer here.
  • Appid=” + bingAPIKey +” – the AppID we’ve got from the BING website, explained previously
  • query=” + keyWords + “ – the search query keywords
  • sources=web – the type of source. Possible source types can be found here.

7. Before we continue with writing the last part of the script, lets see what search result BING will send us back:

{"SearchResponse":
    {
        "Version":"2.2",
        "Query":
            {
                "SearchTerms":"hajan selmani aspnet weblog"
            },
        "Web":
            {
                "Total":16,
                "Offset":0,
                "Results":[
                    {
                        "Title":"Hajan's Blog",
                        "Description":"microsoft asp.net development blog ... Create nice animation on your ASP.NET Menu control using jQuery by hajan",
                        "Url":"http:\/\/weblogs.asp.net\/hajan\/",
                        "CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=hajan+selmani+aspnet+weblog&d=4760941354158132&w=c9535fb0,d1d66baa",
                        "DisplayUrl":"weblogs.asp.net\/hajan",
                        "DateTime":"2011-03-03T18:24:00Z"
                    },
                    {
                        "Title":"codeasp.net",
                        "Description":"... social community for ASP.NET bloggers - we are one of
                                        the largest ASP.NET blog ... 2\/5\/2011 1:41:00 AM by Hajan Selmani - Comments ...",
                        "Url":"http:\/\/codeasp.net\/blogs\/hajan",
                        "CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=hajan+selmani+aspnet+weblog&d=4826710187311653&w=5b41c930,676a37f8",
                        "DisplayUrl":"codeasp.net\/blogs\/hajan",
                        "DateTime":"2011-03-03T07:40:00Z"
                    }
                    ...
                        ]
            }
    }

To get to the result of the search response, the path is: SearchResponse.Web.Results, where we have array of objects returned back from BING.

8. The final part of the code that performs the search is

$("#<%= btnSearch.ClientID %>").click(function (event) {
    event.preventDefault();
    var keyWords = $("#<%= txtSearch.ClientID %>").val();
    var encodedKeyWords = encodeURIComponent(keyWords);
    //alert(keyWords);
    var url = "http://api.search.live.net/json.aspx?JsonType=callback&JsonCallback=?&Appid="+ bingAPIKey
             + "&query=" + encodedKeyWords
             + "&sources=web";
    $.getJSON(url, function (data) {
        $("#result").html("");
        $("#bingSearchTemplate").tmpl(data.SearchResponse.Web.Results).appendTo("#result");
    });
});

The search happens once we click the Search Button with id btnSearch. We get the keywords from the Text Box with id txtSearch and then we use encodeURIComponent. The encodeURIComponent is used to encode the special characters such as: , / ? : @ & = + $ #, which might be part of the search query string. Then we construct the URL and call it using HTTP GET. The callback function returns the data, where we first clear the html inside div with id result and after that we render the data.SearchResponse.Web.Results array of objects using template with id bingSearchTemplate and append the result into div with id result.

9. The bingSearchTemplate Template

<script id="bingSearchTemplate" type="text/html">
    <div class="item">
        <div class="title"><a href="${Url}" target="_blank">${Title}</a></div>
        <div class="date">${DateTime}</div>
        <div class="searchresult">
            <div class="description">
            ${Description}
            </div>
            <div class="url">
                <a href="${Url}" target="_blank">${Url}</a>
            </div>
        </div>
    </div>
</script>

If you paid attention on the search result structure that BING creates for us, you have seen properties like Url, Title, Description, DateTime etc. In the above defined template, you see the same wrapped into template tags. Some are combined to create hyperlinked URLs.

10. THE END RESULT

 

As you see, it’s quite simple to use BING API and make search queries with ASP.NET and jQuery.

In addition, if you want to make instant search, replace this line:

$(“#<%= btnSearch.ClientID %>”).click(function(event) {
       event.preventDefault();

with

$(“#<%= txtSearch.ClientID %>”).keyup(function() {

This will trigger search on each key up in your keyboard, so if you use this approach, you won’t event need a search button.

If it’s your first time working with BING API, it’s very recommended to read the following API Basics PDF document.

Hope this was helpful blog post for you.

© ASP.net Weblogs or respective owner

Related posts about AJAX

Related posts about ASP.NET