TheyWorkForYou API testing

This form, upon submission, uses the TheyWorkForYou API to fetch the constituency name for that postcode. And then does another lookup to work out what colour background to make the box, dependent upon the MP’s party. :)

This really only works with JavaScript; otherwise, the postcode will be sent to TheyWorkForYou to show you the MP’s page.

Request: http://www.theyworkforyou.com/api/getConstituency?key=key&output=js&callback=fn&postcode=postcode

Response: response.name contains the constituency name upon success, response.error contains an error string otherwise.

Source code

function call_api(fn, callback, vars) {
    var s = document.createElement('script');
    var url = 'http://www.theyworkforyou.com/api/'
        + fn + '?key=KEY&callback=' + callback;
    for (var i in vars) {
        url += '&' + i + '=' + encodeURIComponent(vars[i]);
    }
    s.setAttribute('src', url);
    s.setAttribute('type', 'text/javascript');
    document.getElementsByTagName('head')[0].appendChild(s);
}

function lookup(pc) {
    call_api('getConstituency', 'const_received', { postcode: pc } );
}

function const_received(r) {
    if (r.error) {
        display('<i>Error:</i> ' + r.error, 'white', 'red');
        return;
    }
    name = r.name;
    call_api('getMP', 'mp_received', { constituency: name } );
}

function mp_received(r) {
    if (r.error) {
        display('<i>Error:</i> ' + r.error, 'white', 'red');
        return;
    }
    var text = name + '<br><a href=\"http://www.theyworkforyou.com/mp/?c='
        + encodeURIComponent(name) + '\">' + 'TheyWorkForYou</a>';
    if (r.party == 'Labour') {
        display(text, '#ffcccc', '#ff0000');
    } else if (r.party == 'Conservative') {
        display(text, '#ccccff', '#9999ff');
    } else if (r.party == 'Liberal Democrat') {
        display(text,'#ffffcc', '#ffff00');
    } else {
        display(text, 'white', 'black');
    }
}

function display(text, bg, border) {
    var d = document.getElementById('result');
    d.innerHTML = text;
    d.style.backgroundColor = bg;
    d.style.borderColor = border;        
    d.style.display = 'block';
}

Navigation