Answered Bing Search with Ajax - same origin policy

  • Thursday, August 02, 2012 6:51 PM
     
     

    Hi -

    Here in the forum topics, I have seen a couple of different times where client-side code using jQuery is shown with a comment that says how that code worked for the poster. This post and this post both show the same Javascript code sample that makes an AJAX call to https://api.datamarket.azure.com/Bing/Search/etc/etc.

    Putting aside the security concern for a moment - that is, you're putting your account key in client-side code where anybody can read it - I don't understand how this can work due to the same origin policy.

    Can someone help me understand that? I know there's some new ways of doing cross-domain requests (XDR) with IE8 and above or (I think - not sure) you can allow it in earlier versions of IE by putting your desired site in the trusted security zone, but how does the technique shown in these posts work in a browser-independent way? Or does it?

    Thanks. Victor David

    Updated: I've tried the code that Arwind provided. In Firefox, the success handler does get called, but there is no responseText in the request object that gets passed to the handler, that is: request.responseText is undefined.

    In IE8, nothing happens. The beforeSend callback (to set the header) doesn't fire.

    I expected this behavior, more or less. That is, it doesn't work because I'm attempting to violate the same-origin policy. So, no data for me.

    But I'd really like to understand how it can work for others. Am I missing some piece?


    • Edited by VictorDavid Thursday, August 02, 2012 7:55 PM
    • Edited by VictorDavid Friday, August 03, 2012 1:41 AM
    •  

All Replies

  • Friday, August 03, 2012 3:50 AM
    Moderator
     
     Answered Has Code

    Hi,

    I've test it at my side, actually the code is used to show how to send Ajax request to Bing search API, if you need the code work immediately, i suggest you change the code like this:

        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.2.js" type="text/javascript">    </script>
        <script type="text/javascript">
    
            function setHeader(xhr) {
                xhr.setRequestHeader('Authorization', 'Basic <:Key>');
            }
    
            var fetchIndex = 0;
    
            function GetBing() {
                //Build up the URL for the request
                var requestStr = "https://api.datamarket.azure.com/Data.ashx/Bing/Search/Image?Query=%27hi%27&$top=50&$format=Json";
    
                //Return the promise from making an XMLHttpRequest to the server
                $.ajax({ url: requestStr, beforeSend: setHeader
                })
                    .done(
                //Callback for success
                    function (request) {
                        var results = [], count;
    
                        // Works for FireFox
                        var obj = JSON.parse(request);
                        // Wokrs for IE 10 and Chrome
                        var obj = request;
                        // Verify if the service has returned images
                        if (obj.d !== undefined) {
                            var items = obj.d.results;
    
                            // Data adapter results needs an array of items of the shape:
                            for (var i = 0, itemsLength = items.length; i < itemsLength; i++) {
                                var dataItem = items[i];
                                results.push({
                                    key: (fetchIndex + i).toString(),
                                    data: {
                                        title: dataItem.Title,
                                        thumbnail: dataItem.Thumbnail.MediaUrl,
                                        width: dataItem.Width,
                                        height: dataItem.Height,
                                        linkurl: dataItem.MediaUrl
                                    }
                                });
                            }
                            document.write(results[1].data.title);
    
                        }
                        else {
    
                        }
                    });
            }
      </script>

    Here i need clarify something, notice these code in code block:

                        // Works for FireFox
                        var obj = JSON.parse(request);
                        // Wokrs for IE 10 and Chrome
                        var obj = request;

    FireFox (I use FireFox 14 at my side) can not Parse Json string variable without JSON.parse method, so here you need a code logic to judge browser type to make the code works for these 3 browsers.

    And the JQuery code is also not works for IE 8 & IE 9 becuase cross-domain origin is not supported, so in IE 8 & IE 9 environment, the recommended way is use Server-side code (HttpWebRequest).

    Hope his helps.


    Please mark the replies as answers if they help or unmark if not. If you have any feedback about my replies, please contact msdnmg@microsoft.com Microsoft One Code Framework

    • Marked As Answer by VictorDavid Monday, August 06, 2012 2:30 PM
    •  
  • Friday, August 03, 2012 6:22 AM
     
     Answered

    Hi Victor,

    That's exactly the same problem we have run into.

    If you use json, the request is fired and authenitcated in Firefox, but not IE. If you use jsonp, the request is fired in both browsers but you cannot authenticate because it's handled in kind of a script-tag. So actually it seems that only a local php "webservice" can solve this issue - I tried to create a sample and it works. We are not sure if there is any possibility to use OAuth in that case, still waiting for an answer. :-)

    http://social.msdn.microsoft.com/Forums/en-US/DataMarket/thread/d0bf262d-555a-49c8-9d32-39090e75a714

    Best regards
    yukiko

    • Marked As Answer by VictorDavid Monday, August 06, 2012 2:30 PM
    •  
  • Friday, August 03, 2012 6:35 PM
     
     

    Thanks Arwind and Yukiko, that helps a lot. I understand a lot better now!

    Victor David