Hello, you need to enable JavaScript to use this network.

Please check your browser settings or contact your system administrator.

Ning Developer Network

Quick Intro

When building client-side functionality into your Ning Sites with Javascript you may need to access information about the Site, the current user, their friends list and other Playground data. Ning automatically preloads some of this data for you, and the rest is easily accessible with simple HTTP calls.

ning.CurrentApp

A preloaded array containing the main attributes of the current Ning Site is available as ning.CurrentApp. (Note that altering this array will not affect the attributes stored in the Playground.)

Here's an example:

ning.CurrentApp = {
name: "Wombats 4 Everyone",
owner: "brianm",
id: "wombats",
url: "http://wombats.ning.com/"
iconUrl: 'http://api.ning.com/icons/appatar/wombats?default=76',
viewSourceUrl: "http://www.ning.com/view-source.html?appUrl=wombats",
};

The attributes in detail:

  • name - The published name of the Site, used to describe it
  • owner - The username of the Site owner
  • id - The short name of the Site, as featured in its ning.com URL
  • url - The preferred URL for accessing the Site. If the owner has paid for the domain mapping Premium Service, this URL will be the mapped domain; otherwise it will be the ning.com URL
  • iconUrl - URL for the Site's icon image
  • viewSourceUrl - URL to view the source of the Site, if public

ning.CurrentProfile

The public profile data of the current user is available as ning.CurrentProfile. As with ning.CurrentApp, altering this array has no effect on the stored profile. Unlike ning.CurrentApp, however, it's not always available: if the current user is not signed in, ning.CurrentProfile will be null. As such, always make sure to test its existence before diving into it.

Here's an example of the array structure:

ning.CurrentProfile = {
id: 'brianm',
fullName: "Brian McCallister",
description: "I'm the overlord of cuteness",
photoUrl: 'http://api.ning.com/icons/profile/brianm?default=8765',
profileUrl: "http://browse.ning.com/any/brianm",
birthDate: 1902-07-03T13:00:00.000Z,
zipcode: 94301,
developer: true,
friendCount: 3
};

The attributes in detail:

  • id - The username associated with the profile.
  • fullName - The user's full name, if available.
  • description - The user's self-entered personal description, if available.
  • photoUrl - URL of the user's uploaded avatar image.
  • profileUrl - URL of the public user profile page.
  • birthDate - The user's date of birth in ISO8601 format, if available
  • zipcode - The user's home zipcode, if available
  • developer - Boolean showing whether the user has self-identified as a Ning developer
  • friendCount - The number of reciprocated friend connections

Detecting the Site Owner

A perfect example of using both ning.CurrentApp and ning.CurrentProfile together is the case of working out whether the current user is also the Site's owner. Here's how you do it:

if (ning.CurrentProfile 
&& ning.CurrentProfile.id == ning.CurrentApp.owner)
{
// it's the Site owner
} else {
// it's someone else
}

This is a great way to expose admin features in your Site's interface dynamically. However, bear in mind that the user can run their own Javascript code in the browser to change the data in both ning.CurrentProfile and ning.CurrentApp. As such, you should validate any privileged admin actions with server-side code before executing them.

Accessing the User's Friends List

Information about the user's friend relationships and address book can be accessed through the Ning REST API. This is done by sending HTTP GET queries to the Ning Playground and retrieving data in JSON format, which can be easily interpreted by Javascript.

Here's an example URL for fetching all of Tim's friends:

http://SITENAME.ning.com/xn/rest/1.0/profile:Tim/contact(relationship='friend')

(Like most Ning REST API calls, the call to fetch friend list data can be made to any Ning Site. Replace SITENAME above with the name of your Site.)

The data retrieved is a JSON array which can be evaluated and manipulated directly in Javascript. Here's an example array that might be returned by the query above:

{"contacts":
    {"total":"2","values":[
{"createdDate":"2006-06-02T23:48:23.179Z",
"updatedDate":"2006-06-06T01:25:40.623Z",
"contactRelationship":"friend",
"screenName":"diego",
"photoUrl":"http:\/\/api.ning.com\/icons\/profile\/31179?default=8265",
"profileUrl":"http:\/\/browse.ning.com\/any\/diego",
"id":"diego",
"relationship":{
"friend":"true",
"description":"friend"}
},
{"createdDate":"2006-06-06T22:35:01.011Z",
"updatedDate":"2006-06-10T18:44:08.705Z",
"contactRelationship":"friend",
"screenName":"steve",
"photoUrl":"http:\/\/api.ning.com\/icons\/profile\/31259?default=9902",
"profileUrl":"http:\/\/browse.ning.com\/any\/steve",
"id":"steve",
"relationship":{
"friend":"true",
"description":"friend"}
}
],
"end":"2",
"begin":"0"}
}

For the full details of the data that can be accessed through the REST API and the query syntax you can use in URLs, check out our REST API documentation.

Pulling it all together in code

Here's some sample Javascript to fetch and display the current user's friends in a drop-down list - useful for "Send this to a friend" features. Note that we're using the super-powerful Dojo function dojo.io.bind to make the REST API call, fetch and parse the JSON data that's returned, and invoke the list display once the data's back. (For more information about Dojo, check out our introduction.)

dojo.require('dojo.io');
var username = ning.CurrentProfile 
? ning.CurrentProfile.id
: 'ning';
var appURL = window.location.host;

// this is the URL to grab the list of contacts
var requestURL = 'http://' + appURL + '/xn/rest/1.0/profile:' +
username + "/contact(relationship='friend')";

// load the contacts list from the server, parse it,
// output a list of contacts to the #friendslist DIV
dojo.io.bind({
url: requestURL,

load: function(type, data, evt){
var formdiv = dojo.byId('sendtoform');
if (data.errors) {
alert(data.errors.error);
} else if (data.contacts.total == 0) {
formdiv.innerHTML = "<b>Sorry, can't send without friends!</b>";
} else {
var formhtml = "<b>Send to a friend:</b> <select class='text'>";
for (i in data.contacts.values) {
friend = data.contacts.values[i];
formhtml += "<option value='"+friend.id+"'>";
formhtml += friend.screenName + "</option>";
}
formhtml += "</select>";
formdiv.innerHTML = formhtml;
}
},

error: function(type, error){
var formdiv = dojo.byId('sendtoform');
formdiv.innerHTML = "<b>Error:</b> <tt>" + error + "</tt>";
},

// the list will be automatically parsed as JSON
mimetype: "text/json"
});

Introduction to Dojo and Trimpath JST

Dojo is a featureful and powerful toolkit for the rapid-development of Javascript apps with cutting-edge features, including those known collectively as Ajax. Currently in active development, it's an Open Source project being worked on by many of the leading lights of the Javascript community. Ning makes extensive use of Dojo to provide features such as the Ningbar. We also make Dojo available for Site developers looking to further enhance their Sites with Javascript-powered features, along with another useful Open Source library, the Trimpath templating system.

This document provides a brief overview of some of Dojo and Trimpath's features and how you can use them in the Ning Playground.

Dojo Features

The Dojo Toolkit is rapidly gaining popularity due to the way it makes writing Javascript code considerably easier. Not only are its features powerful and applicable to code development on many different levels, but they're implemented in a cross-platform way to ensure they work on as many different web browsers as possible.

Here are a few of the features that Dojo gives the Javascript developer:

  • Utility routines to enhance Javascript's power at the language level, dealing with arrays, strings and functions
  • Tools for easier manipulation of the Document Object Model, HTML and CSS
  • A selection of cool dynamic effects to enhance your pages, including animation and drag & drop
  • A set of ready-made widgets to use in forms, and tools to create and reuse new ones
  • A set of useful collection classes
  • Functions to simplify HTTP communication from within code and the dynamic loading of resources

For in-depth documentation and demos of Dojo's many features, check out dojotoolkit.org.

Namespaces

To avoid accidental clashes with your own function and variable names, Dojo puts its functions in their own namespaces. For example, the trim(str) function removes whitespace characters from the start and end of the string str. Because it's a string-manipulation routine, it lives in dojo.string and is invoked like this:

var trimmedString = dojo.string.trim(myString);

Ning's own Javascript functions have a namespace called, unsurprisingly, ning. You're welcome to explore it and make use of the things that you find - note, however, that properties and methods in the ning._ namespace are continually subject to change, so best left alone.

Quick Tricks

Dojo's packed full of nifty features, but you don't have to learn the whole toolkit before you can start using it. If you're writing a lot of Javascript, try using these functions to save you some time:

dojo.byId(id)
The quickest way to grab a DOM node by its name. Dojo has a bunch of useful functions to make it easier to deal with the DOM - check out the dojo.dom documentation.
dojo.string.escape(type,string)
Escapes string so that it can be used in type, where type can be any of XML, HTML, regexp, javascript, SQL or ascii. Saves all that mucking about with regular expressions.
dojo.addOnload(function)
A great way to add code to the body.onLoad handler without clobbering what's already there.
dojo.dnd
This module makes it incredibly easy to create powerful drag & drop interfaces in just a handful of lines. Here are the dojo.dnd docs.
dojo.io.bind(options)
This is a super-powerful tool for doing dynamic HTTP calls (such as the XMLHTTPRequest provides) and giving your sites that extra Ajax whoosh. dojo.io.bind() doesn't just make it easy to do, it makes it easy to do properly - so you can handle errors and don't have to break the back button. Check out this intro to Dojo IO.

Packages

One of Dojo's niftiest features is the way it's split into different loadable modules known as packages. You don't need to include the whole of Dojo in your site to use one aspect of it; instead, you can just load the one module you need. By omitting unused parts of the Toolkit you can make page loads considerably faster.

The package names are the same as the namespaces that they define. All of the dojo.string functions are in the package named dojo.string.

By default, Ning doesn't preload the whole of Dojo for you. To load a particular Dojo package, use the dojo.require function like so:

dojo.require("dojo.packagename");

It's wise to require any package that you'll need before you use it, just to be sure that it's loaded. If it's already loaded it won't be loaded again, so you don't need to worry about wasting time.

You can also place require calls inside conditional blocks so that packages are only loaded at the point if and when they're needed. Ning uses this technique for some of the code in Ningbar panels.

Trimpath Javascript Templates

Outputting large amounts of custom HTML with dynamic data can be a pain in Javascript: it either involves lots of time-consuming DOM manipulation or the ugly gluing-together of strings. Fortunately, the Trimpath Javascript Template engine (herein known as JST) makes things much simpler.

JST is a simple but powerful templating language designed for the fast interpolation of values into strings. Here's a very simple example:

dojo.require('trimpath.template'); // make sure it's loaded
var myData = { firstname : "Luther", lastname: "Blissett" };
var myStr = "Hello there, ${firstname} ${lastname|capitalize}!";
var result = TrimPath.parseTemplate(myStr).process(myData);
// result now contains "Hello there, Luther BLISSETT!"

As you can see, JST makes it easy not just to interpolate variable data but to perform modifications on the data as it's output. And that's just for starters! Here are some other JST features:

  • Conditional blocks
  • Loops
  • Macros
  • Embedded Javascript

Just like Dojo, Ning makes Trimpath JST available to all by default. You can find more information and examples for JST usage in the JST documentation.

About This Discussion

Started Oct 4 by:

Diego Diego
View Discussions »

About Ning Developer Network

Diego Diego created this social network on Ning.

Quick Links

Ning Developer Network brought to you by Diego © 2007 Report an Issue | Feedback | Privacy | Terms of Service

Spread the word! Get a Ning Developer Network badge