« Example of how to use "getElementsByTagName" | Main | Movies4Me »

How to Use Dynamic Javascript and JSON

Normally, you cannot use XHR to retrieve data from a server that is not at the same location as the web page that you are on. This limitation can be overcome by using Dynamic Javascript.

Dynamic javascript takes advantage of the fact that scripts can be downloaded into a web page from external websites.

Here is an example of how to do this. Feel free to make your own example using the "_jsoncount.php" page but keep in mind that useful data will only be returned if the location is in our "favorites" database. You can go to http://www.myfavoriteplaces.org and add a few favorites to ensure that you can retrieve a popularity result.

The script returns data in JSON, so take a look at how easily the getPopular function references the data compared to trying to access data from xml.

First we need to create the dynamic javascript element that is inserted into the page.
Once the script tag is created, the browser downloads the javascript from the
supplied url. Even though the url is for a *.php page, a javascript function
is actually returned from it.

This snip of javascript creates the dynamic script tag (the "title" variable in this script contains the name of a business being queried for popularity).

//-- URL of remote script to download.
var dynaurl = "http://www.myfavoriteplaces.org/scripts/_jsoncount.php?favoriteid=" + title;

//-- Create the dynamic script tag
var dScript = null;

   dScript = document.createElement("script");
   dScript.src = dynaurl;
   dScript.id = "xssScript";

//-- Find place in document to insert the new script tag. Script call is executed
//-- as soon as the script is appended into the document
var topHead = document.getElementById("head");
topHead.appendChild(dScript);

This is the script tag that the browser creates:

<script id="xssScript" src="http://www.myfavoriteplaces.org/scripts/_jsoncount.php?favoriteid=Burger King" />

This is the javascript that is returned to the browser:

getPopular([ {"title":"Burger King", "popularity":1 }]);

Now you might wonder what this javascript is supposed to do. You'll notice that this javascript is actually calling a function called "getPopular" and not declaring a function.

This means that a function called "getPopular" must already exist. The existing function is then passed the array that is passed back with the getPopular call from the returned javascript.

Here is an example of an existing function declaration that handles the data returned from the remote server:

function getPopular(popular) {
   var vLocation = popular[0].title;
   var vPopularity = popular[0].popularity;
  
   alert(vLocation + " is liked by " + vPopularity + " member(s)");
}


I hope that this is useful example of using dynamic javascript and JSON. Have fun!

Archives