2

I would like to use vanilla JavaScript to access some MeetUp API data. I am using the following code on my website:

function addScript(src) {
    console.log(src);
    var s = document.createElement( 'script' );
    s.setAttribute( 'src', src );
    document.body.appendChild( s );
}

addScript('https://api.meetup.com/2/groups?callback=?&sign=true&member_id=8377069&page=20&api&key=API_KEY_GOES_HERE&only=name,link');

I am using a script tag to access the data to avoid cross domain issues. I appreciate this could be solved using jQuery but I do not want to use any external libs.

The above code returns this error:

Uncaught SyntaxError: Unexpected token :

I believe this is because JSON format is returned. How can I fix this but at the same time still access the JSON data. Any help much appreciated.

Example link: http://jsfiddle.net/londonfed/7ms44ft6/

londonfed
  • 1,170
  • 2
  • 12
  • 27

2 Answers2

4

Since the meetup API supports a callback parameter, create a global function (in window) and set the callback parameter to the function name:

function addScript(src) {
    console.log(src);
    var s = document.createElement( 'script' );
    s.setAttribute( 'src', src );
    document.body.appendChild( s );
}

// Callback for loading api data:
window.apiCallback = function(data) {
     // do what you want with the data
     alert(data.results[0].name);
}
addScript('https://api.meetup.com/2/groups?callback=apiCallback&sign=true&member_id=8377069&page=20&api&key=API_KEY_GOES_HERE&only=name,link');
londonfed
  • 1,170
  • 2
  • 12
  • 27
Bouke Versteegh
  • 4,097
  • 1
  • 39
  • 35
1

You need to specify a callback parameter in your URL which will be the same as the name of the function that will be used to process the returned data:

function processJSONP(json) {
  console.log(json.results);
}

addScript('https://api.meetup.com/2/groups?callback=processJSONP&sign=true&member_id=8377069&page=20&api&key=5746c1b12324669953258703b11&only=name,link');

Remember that results is an array that you need to loop over.

Andy
  • 61,948
  • 13
  • 68
  • 95