YUI recommends YUI 3.

YUI 2 has been deprecated since 2011. This site acts as an archive for files and documentation.

YUI Library Home

YUI Library Examples: Get Utility: Getting a Script Node with JSON Data from a Web Service

Get Utility: Getting a Script Node with JSON Data from a Web Service

This example employs the YUI Get Utility in a simple use case: retrieving JSON data from a cross-domain web service. While this is a relatively common usage, it's important to understand the security ramifications of this technique. Scripts loaded via the Get Utility (or any other "script node" solution) execute immediately once they are loaded. If you do not fully control (or fully trust) the script's source, this is not a safe technique and it can put the security of your users' data at risk. (For more information on the dangers of cross-site scripting [XSS] exploits, check out the Wikipedia entry on this subject.)

Here, we will use a trusted Yahoo! Search web service called Site Explorer to return a list of inbound links for a given URL. The principal difference between this example and similar examples using YUI Connection Manager is that this technique does not require a server-side proxy. The browser connects directly to the third-party web service without bouncing through a proxy page as is required when using the XMLHttpRequest object (on which Connection Manager relies).

Using the Get Utility to Get a Script File with JSON-formatted Contents

Here, we'll use the YUI Get Utility to retrieve data via the Yahoo! Search Site-Explorer web service, one of many Yahoo! APIs that support JSON.

This example has the following dependencies:

1<link rel="stylesheet" type="text/css" href="http://yui.yahooapis.com/2.9.0/build/button/assets/skins/sam/button.css" /> 
2<script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script> 
3<script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/element/element.js"></script> 
4<script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/button/button.js"></script> 
5<script type="text/javascript" src="http://yui.yahooapis.com/2.9.0/build/get/get.js"></script> 
view plain | print | ?

First, we create a plain HTML form that will work for users who do not have JavaScript enabled:

1<div id="container"
2 
3    <!--Use a real form that works without JavaScript:--> 
4    <form method="GET" action="http://siteexplorer.search.yahoo.com/advsearch" id="siteExplorer"
5 
6        <label for="searchString">Site URL:</label> <input type="text" name="searchString" id="p" value="http://developer.yahoo.com/yui" size="40"
7         
8        <input type="hidden" name="bwm" value="i"
9        <input type="hidden" name="bwms" value="p"
10     
11        <input type="submit" id="getSiteExplorerData" value="Click here to get JSON data."
12     
13    </form> 
14 
15    <div id="results"
16        <!--JSON output will be written to the DOM here--> 
17         
18    </div> 
19</div> 
view plain | print | ?

With this in place, we can progressively enhance the form to create an in-page interaction for users with JavaScript turned on.

The most important JavaScript piece here is the method that we fire on form submission. This method triggers our call to the Get Utility. This method, called getSiteExplorerData, accomplishes four things:

  1. It loads a transitional state for the display, alerting the user to the fact that data is being retrieved as a result of her action (line 7ff);
  2. It prepares the URL that will be passed to the Get Utility (line 13ff);
  3. It calls the Get Utility, passing in the URL of the script resource to load (in this case, the URL of our web service with the relevant paramaters assembled in the querystring) (line 22ff);
  4. It specifies the callback (line 23) and the scope in which the callback should run (line 24). Note that in this example the web service itself provides callback functionality, allowing us to pass a globally accessible callback function name as one of the parameters of the REST API; you can see this reference in line 16 below. As a result, we're making direct use of the intrinsic web service callback in this example and just stubbing out the built-in Get Utility callback for the sake of illustration.

1//function to retrieve data from Yahoo! Site Explorer web service -- 
2// http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html 
3var getSiteExplorerData = function() { 
4    YAHOO.log("Button clicked; getSiteExplorerData firing.""info""example"); 
5 
6    // block multiple requests 
7    if (loading) { 
8        return
9    } 
10    loading = true
11     
12    //Load the transitional state of the results section: 
13    elResults.innerHTML = "<h3>Retrieving incoming links for " + 
14        Dom.get("searchString").value + ":</h3>" + 
15        "<img src='http://l.yimg.com/a/i/nt/ic/ut/bsc/busybar_1.gif' " + 
16        "alt='Please wait...'>"
17     
18    //prepare the URL for the Yahoo Site Explorer API: 
19    var sURL = "http://search.yahooapis.com/SiteExplorerService/V1/inlinkData?" + 
20        "appid=3wEDxLHV34HvAU2lMnI51S4Qra5m.baugqoSv4gcRllqqVZm3UrMDZWToMivf5BJ3Mom" + 
21        "&results=20&output=json&omit_inlinks=domain" + 
22        "&callback=YAHOO.example.SiteExplorer.callback" + 
23        "&query=" + encodeURIComponent(Dom.get("searchString").value); 
24     
25    //This simple line is the call to the Get Utility; we pass 
26    //in the URL and the configuration object, which in this case 
27    //consists merely of our success and failure callbacks: 
28    var transactionObj = Get.script(sURL, { 
29        onSuccess: onSiteExplorerSuccess, 
30        onFailure: onSiteExplorerFailure, 
31        scope    : this 
32    }); 
33     
34    //The script method returns a single-field object containing the 
35    //tranaction id: 
36    YAHOO.log("Get Utility transaction started; transaction object: " + YAHOO.lang.dump(transactionObj), "info""example"); 
37 
38    // keep track of the current transaction id.  The transaction will be 
39    // considered complete only if the web service callback is executed. 
40    current = transactionObj.tId;  
41
view plain | print | ?

The full JavaScript codeblock for this example reads as follows:

1//create a namespace for this example: 
2YAHOO.namespace("example.SiteExplorer"); 
3 
4//This example uses the "Module Pattern"; a full explanation of  
5//this pattern can be found on yuiblog: 
6// http://yuiblog.com/blog/2007/06/12/module-pattern 
7YAHOO.example.SiteExplorer = function() { 
8 
9    //set up some shortcuts in case our typing fingers 
10    //get lazy: 
11    var Event = YAHOO.util.Event, 
12        Dom = YAHOO.util.Dom, 
13        Button = YAHOO.widget.Button, 
14        Get = YAHOO.util.Get, 
15        elResults = Dom.get("results"), 
16        tIds = {}, 
17        loading = false
18        current = null
19         
20    // We use the Get Utility's success handler in conjunction with 
21    // the web service callback in order to detect bad responses  
22    // from the web service. 
23    var onSiteExplorerSuccess = function(o) { 
24 
25        // stop blocking requests 
26        loading = false
27 
28        // A success response means the script node is inserted.  However, the 
29        // utility is unable to detect whether or not the content of the script 
30        // node is correct, or even if there was a bad response (like a 404 
31        // error).  To get around this, we use the web service callback to 
32        // verify that the script contents was correct. 
33        if (o.tId in tIds) { 
34YAHOO.log("The Get Utility has fired the success handler indicating that the " + 
35          "requested script has loaded and is ready for use.""info""example"); 
36        } else { 
37YAHOO.log("The Get utility has fired onSuccess but the webservice callback did not " + 
38          "fire.  We could retry the transaction here, or notify the user of the " + 
39          "failure.""info""example"); 
40        } 
41 
42    } 
43 
44    var onSiteExplorerFailure = function(o) { 
45YAHOO.log("The Get Utility failed.""info""example"); 
46    } 
47     
48    //function to retrieve data from Yahoo! Site Explorer web service -- 
49    // http://developer.yahoo.com/search/siteexplorer/V1/inlinkData.html 
50    var getSiteExplorerData = function() { 
51        YAHOO.log("Button clicked; getSiteExplorerData firing.""info""example"); 
52 
53        // block multiple requests 
54        if (loading) { 
55            return
56        } 
57        loading = true
58         
59        //Load the transitional state of the results section: 
60        elResults.innerHTML = "<h3>Retrieving incoming links for " + 
61            Dom.get("searchString").value + ":</h3>" + 
62            "<img src='http://l.yimg.com/a/i/nt/ic/ut/bsc/busybar_1.gif' " + 
63            "alt='Please wait...'>"
64         
65        //prepare the URL for the Yahoo Site Explorer API: 
66        var sURL = "http://search.yahooapis.com/SiteExplorerService/V1/inlinkData?" + 
67            "appid=3wEDxLHV34HvAU2lMnI51S4Qra5m.baugqoSv4gcRllqqVZm3UrMDZWToMivf5BJ3Mom" + 
68            "&results=20&output=json&omit_inlinks=domain" + 
69            "&callback=YAHOO.example.SiteExplorer.callback" + 
70            "&query=" + encodeURIComponent(Dom.get("searchString").value); 
71         
72        //This simple line is the call to the Get Utility; we pass 
73        //in the URL and the configuration object, which in this case 
74        //consists merely of our success and failure callbacks: 
75        var transactionObj = Get.script(sURL, { 
76            onSuccess: onSiteExplorerSuccess, 
77            onFailure: onSiteExplorerFailure, 
78            scope    : this 
79        }); 
80         
81        //The script method returns a single-field object containing the 
82        //tranaction id: 
83        YAHOO.log("Get Utility transaction started; transaction object: " + YAHOO.lang.dump(transactionObj), "info""example"); 
84 
85        // keep track of the current transaction id.  The transaction will be 
86        // considered complete only if the web service callback is executed. 
87        current = transactionObj.tId;  
88    } 
89    return { 
90        init: function() { 
91                 
92            //suppress default form behavior 
93            Event.on("siteExplorer""submit"function(e) { 
94                Event.preventDefault(e); 
95                getSiteExplorerData(); 
96            }, thistrue); 
97         
98            //instantiate Button: 
99            var oButton = new Button("getSiteExplorerData"); 
100            YAHOO.log("Button instantiated.""info""example"); 
101        }, 
102 
103        callback: function(results) { 
104            YAHOO.log("Web service returned data to YAHOO.example.SiteExplorer.callback; beginning to process.""info""example"); 
105 
106            // Mark the transaction as complete.  This will be checked by the onSuccess 
107            // handler to determine if the transaction really succeeded. 
108            tIds[current] = true
109             
110            //work with the returned data to extract meaningful fields: 
111            var aResults = results.ResultSet.Result; 
112            var totalLinks = results.ResultSet.totalResultsAvailable; 
113            var returnedLinkCount = results.ResultSet.totalResultsReturned; 
114             
115            if(aResults) {//there are inbound links; process and display them: 
116             
117                //write header and open list of inbound links:           
118                var html = "<h3>There are " + 
119                    totalLinks +  
120                    " inbound links for this page; here are the first " +  
121                    returnedLinkCount + 
122                    ":</h3><ol>"
123                 
124                //process list of inbound links: 
125                for (var i=0; i < aResults.length; i++) { 
126                    html += "<li><strong>" + 
127                        aResults[i].Title + 
128                        ":</strong> <a href='" + 
129                        aResults[i].Url + 
130                        "'>" + aResults[i].Url + 
131                        "</a></li>"
132                } 
133                 
134                //close list of inbound links 
135                html += "</ol>"
136                 
137            } else {//no inbound links exist for this page: 
138             
139                var html = "<h3>There are no inbound links for the page specified.</h3"
140                 
141            } 
142             
143            //insert string into DOM: 
144            elResults.innerHTML = html; 
145        } 
146    } 
147}(); 
148 
149//Initialize the example when the DOM is completely loaded: 
150YAHOO.util.Event.onDOMReady( 
151    YAHOO.example.SiteExplorer.init,  
152    YAHOO.example.SiteExplorer,         //pass this object to init and... 
153    true);                              //...run init in the passed object's 
154                                        //scope 
view plain | print | ?

Configuration for This Example

You can load the necessary JavaScript and CSS for this example from Yahoo's servers. Click here to load the YUI Dependency Configurator with all of this example's dependencies preconfigured.

YUI Logger Output:

Logger Console

INFO 59ms (+0) 4:11:25 AM:

LogReader instance0

LogReader initialized

INFO 59ms (+1) 4:11:25 AM:

Get

Appending node: ../../../2.x/build/event-mouseenter/event-mouseenter-min.js

INFO 58ms (+0) 4:11:25 AM:

Get

attempting to load ../../../2.x/build/event-mouseenter/event-mouseenter-min.js

INFO 58ms (+58) 4:11:25 AM:

Get

_next: q0, loaded: undefined

INFO 0ms (+0) 4:11:25 AM:

global

Logger initialized

More Get Utility Resources:

Copyright © 2011 Yahoo! Inc. All rights reserved.

Privacy Policy - Terms of Service - Copyright Policy - Job Openings