JSONP and CSS Selectors (Part 1)

Mar 22, 2010
Episode 17
Jim shows you how to call 3rd party web services using JSONP and Nick goes over some basic CSS selectors. Next week, Nick will cover the selectors that are new in CSS3.
Spotlight

Thanks to those who make Doctype possible!

JSONP

In Episode 12 we took a look at using AJAX to load data from your server without reloading the page. AJAX is a great way to get information into your webpage, but there is one big limitation, you can only use AJAX to load data from the same domain as the original page was loaded on.

So my page could not load data via AJAX from a yahoo web service. This is due to AJAX’s same domain policy which we explained in Episode 3.

Today we’re going to look at a technique from getting data from a remote server that’s called JSONP

Basics

JSONP stands for JSON with Padding. JSON is a data format that is used in many web services because it is a subset of JavaScript syntax, and can be easily evaluated in JavaScript. We’ll get to the padding in a moment.

//JSON
{
  "key": "value",
  "foo": [1, 2, 3.01, "bar"],
  "baz": {
   "fizz": ["buzz"]
 }
}

Since you can’t use XMLHttpRequest to request a resource on another domain, JSONP utilizes the script tag, which can load javascript from any server. We just use javascript to create a script tag with the source being the url of the service we want. The browser will fetch it and execute it.

new XMLHttpRequest('http://google.com/web_service');
//ERROR! Different Domain!    

<script src="http://google.com/web_service"></script>

<!-- Evaluates to... -->

Now if that service only returned us the JSON data, it does us no good, because it just silently evaluates the data, but we don’t get notified that the data is there, and it’s not stored into a variable. That’s where padding comes in.

<script src="http://google.com/web_service">
//We can't access result data!
{"service_results": "..."}
</script>

What we can do is create a function to handle the results. This function must be named and visible from the global scope in order to work. Then we create our SCRIPT Element, set it’s src value to our service url. Inside the url for the service, we tell it the name of our callback. We then append it to the page.

function myCallback(result){
  //Handle result
}

var script = document.createElement('SCRIPT');
script.type = "text/javascript";
script.src = "http://google.com/web_service?callback=myCallback";
document.body.appendChild(script);

The browser will now send the request and the resulting javascript should call our function with the data as the parameter.

/* Web Service Results */
myCallback({"service_results": "..."});
Creating a JSONP Web Service

If you want to create a webservice that supports JSONP, it’s pretty simple. Just check for a callback parameter and if it exists, wrap that name, plus parenthesis around your normal JSON data. If there is no callback parameter, return it as a normal JSON response.

...
$json = json_encode($results);

if($_GET['callback']){
  $json = $_GET['callback'] . '(' . $json . ');';
  // callbackName({"foo": "bar"});
} 
// else return raw JSON

header('Content-type: text/javascript');
echo $json;

Remember because JSONP uses the script element to fetch the data, it is limited to only GET requests. Also it circumvents the same-domain policy and will send the users cookies to the remote server, so if you are creating a JSONP web service be aware you are vulnerable to Cross Site Request Forgery Attacks,

Check out Episode 13 for more information on CSRF attacks.

If you are using an AJAX framework, it may handle all of this for you automatically. For instance jQuery will automatically switch to JSONP style requests if the url is on a different domain. You may need to read the documentation though because you will have to specify how to send the callback name to the web service.

Resources

CSS Selectors

When writing CSS, people tend to stick with the basic selectors, such as simple ID and class selectors. However, there’s a huge variety of CSS selectors available and having a good understand of how they work can help you write much cleaner CSS and do it a lot faster.

Combinators
E F

By putting a space in between two element selectors, you can select any F elements that are descendants of E elements. So for example, using this selector, you could style all the strong tags inside of your paragraph tags.

E > F

Next is the child combinator. This essentially does the same thing as the descendant selector, but with a subtle and important difference. Where as the descendant combinator can select any arbitrary descendants of a parent element, the child selector will only select the descendant if it is a direct child of the parent. So for instance, the previous example of styling strong tags would work exactly the same here. But if the strong tag were inside of a link, it would no longer work, because the strong tags are not direct children of the paragraphs.

E + F

Finally there’s the adjacent sibling combinator. This combinator allows you to select elements that immediately follow one another, and share the same parent. So for example, if you wanted to indent all the paragraphs that follow a paragraph, you could say p + p and apply a text-indent.

Attribute Selectors

It’s easy to select elements based on an ID or a class, but in reality you can select an element based on any other attribute, like the alt attribute on an image or the rel attribute on a link.

E[foo]

The first one is easy. When you use this selector, you can select any element with an attribute "foo." So for example, I could select all the links that have rel attributes.

E[foo="bar"]

If you want to get more specific, you can use this syntax to access the value of an attribute and select based on that. So for example, I could style all the links that have rel attributes set to the value "next."

E[foo~="bar"]

In this case, if the value in quotes is contained anywhere in the attribute, it will be a match. Using this, you could match any title tags that contain a certain word, even if there are other words separated by whitespace. This is different, because in the previous example, you had to have an exact match.

11a Pseudo Classes

Pseudo classes are special selectors that allow you to style things on the page that don’t always match up to a real element.

E:first-line

With the first-line pseudo-class, you can grab the first row of text inside any element. So for example, you could say P:first-line and change the color of the first line of text in a paragraph.

E:first-letter

The first-letter pseudo-class is very similar, except instead of grabbing the entire first row of text, it will only grab the first character. This is useful if you want to create a versal, which is an ornamental first letter in a block of text, that’s typically large in size.

E:first-child

The first-child selector is a bit different than the previous two. This pseudo-class allows you to select the first child element of a parent element E. So for example, if you had a few paragraphs inside a wrapper div and you wanted to change the color of the first paragraph, you could say p:first-child.

Resources