BING Search using ASP.NET and jQuery Ajax

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.

Published Monday, March 7, 2011 2:02 AM by hajan
Filed under: , , , ,

Comments

# re: BING Search using ASP.NET and jQuery Ajax

Monday, March 7, 2011 6:12 AM by Dostava Hrane

Nice example. I have to try it. Thanks!

# re: BING Search using ASP.NET and jQuery Ajax

Friday, April 15, 2011 4:20 PM by vipul

it's good....

i am getting a problem in using keyup fuctionality.....

if u could help me.......

# re: BING Search using ASP.NET and jQuery Ajax

Sunday, April 17, 2011 6:44 AM by hajan

@vipul, can you tell me more specifically what issue do you have with keyup event? Or, maybe you can post your issues on ASP.NET jQuery Forums - forums.asp.net/1223.aspx

Thanks

# re: BING Search using ASP.NET and jQuery Ajax

Monday, May 30, 2011 11:12 AM by bob

Hello Hajan, what would have to be changed to make this return only results for my website?

# re: BING Search using ASP.NET and jQuery Ajax

Tuesday, May 31, 2011 12:52 PM by hajan

Hi bob,

You can add at the end of your search query text this:

site:www.your-webste.com (to restrict the search to the specific site)

or

url:www.your-website.com (to search for specific URL in BING's index)

That will return only the results from your website ;).

Hope this helps.

# re: BING Search using ASP.NET and jQuery Ajax

Tuesday, June 7, 2011 9:33 AM by Benny

i can not download it.would you please share me a copy.

cooleader_xu@hotmail.com

# re: BING Search using ASP.NET and jQuery Ajax

Friday, June 24, 2011 11:46 AM by medyum

thanks for admin wonderful information

# re: BING Search using ASP.NET and jQuery Ajax

Thursday, September 8, 2011 2:19 AM by satyam

Thanks Dude Worked for me.

# re: BING Search using ASP.NET and jQuery Ajax

Friday, June 22, 2012 6:33 PM by Adame

Very nice post. I just stumbled upon your blog and wanted to say that I

have truly enjoyed browsing your blog posts. In any case I will be subscribing on

your feed and I am hoping you write once more very soon!

# re: BING Search using ASP.NET and jQuery Ajax

Sunday, July 8, 2012 3:53 AM by Brownell

Pretty nice post. I just stumbled upon your weblog and wanted to say that

I have really enjoyed surfing around your blog posts. After all I will be subscribing to your

rss feed and I hope you write again soon!

# re: BING Search using ASP.NET and jQuery Ajax

Monday, September 10, 2012 6:17 PM by Dozier

Great post. I was checking constantly this blog and I'm impressed! Extremely useful info specifically the last part :) I care for such info a lot. I was looking for this particular info for a very long time. Thank you and good luck.

# re: BING Search using ASP.NET and jQuery Ajax

Friday, February 22, 2013 1:47 PM by Galvez

You are a very bright person!

Leave a Comment

(required) 
(required) 
(optional)
(required)