Waymas
Waymas

Reputation: 423

Processing a json from challonge api

i'm trying to build a Power Rankings app with the help of Challonge Api, but it seems the JS just keep sending me errors when i retrieve the json.

Test Site

$(document).ready(function(){

$.ajax({
        url: 'https://api.challonge.com/v1/tournaments/3j91s6g1/matches.json',
        type: 'GET',
        dataType: "jsonp",
        success: function (data) {
            // FOR TEST PURPOSE
             $.each(data, function(index, element) {
                $('body').append($('<div>', {
                    text: element.name
                }));
            });
        },
        error : function(error){
            console.log(error)
        }
    });

});

Any ideas?

Upvotes: 0

Views: 2116

Answers (2)

Waymas
Waymas

Reputation: 423

I just decided to use php and had no problems retrieving the JSON

<?php 
    $json = file_get_contents('https://<edited_apikey>@api.challonge.com/v1/tournaments/3j91s6g1/participants.json/');
    $var = json_decode($json,true);
    //echo $var[0][participant][name];
    foreach($var as $p)
    {
    echo $p[participant][name]."<br />";
    
    }
    ?>

Upvotes: 1

bluehexagons
bluehexagons

Reputation: 81

I was searching around for stuff about the Challonge API and happened upon this question by accident, thought I'd give you an answer.

The reason you're hitting an error requesting using JavaScript is because Challonge's API doesn't have cross-origin requests enabled. To prevent a web page from pulling a user's data from any other website using Ajax requests, the web browser checks with the other website to see if it's OK to send the request by looking for cross-origin headers. If you want to learn more, you can check out the Wikipedia article or other sites talking about CORS (cross-origin resource sharing).

Another thing I should add: you generally don't want to share your API key with anyone else, since that's tied directly to your account. The first part of the URL in your question is your username:key, which means that anyone who happens upon this can use it to modify your brackets, etc. This is actually likely a reason why Challonge doesn't allow CORS; people shouldn't be sending these requests from JavaScript anyway since it requires sharing their API key (user with web page, or site owner with users).

You also need to be careful echoing arbitrary text to a web page. I don't know about Challonge's participant name restrictions, but it could lead to a cross-site scripting vulnerability.

Upvotes: 3

Related Questions