Use API JSON to display a URL for an HTML Page - javascript
I am completely new to all of this so please forgive any issues with how I'm describing and name things. I have an HTML page where the user enters a portion of a URL string in order to launch a new window with the complete URL string. I'd rather just lookup the portion of the URL using an API to create a JSON file and find it automatically. Any ideas how I can accomplish this without user intervention?
HTML (contains text box and button to launch a new window, which I would like to bypass this altogether)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Cast Challonge</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function(e) {
var inputvalue = $("#input").val();
window.open(("http://challonge.com/"+inputvalue+"/module?theme=5928&selected-round-
filter=2&show_final_results=0&multiplier=2&show_tournament_name=1&scale_to_fit=1"),"Tournament
Display","width=1280,height=720,resizable=no, toolbar=no, scrollbars=no, menubar=no, status=no,
directories=no");
});
});
</script>
</head>
<body>
<input type="text" value="" id="input">
<button type="button" id="button">Submit Tournament ID</button>
</body>
</html>
My sample API call is as follows:
[
{
"tournament": {
"id": 9838153,
"name": "2021/05/22 Saturday Night 8-Ball",
"url": "BnkSat0522",
"description": "",
"tournament_type": "double elimination",
"started_at": "2021-05-23T07:01:41.429+07:00",
"completed_at": "2021-05-23T12:54:30.331+07:00",
"require_score_agreement": false,
"notify_users_when_matches_open": true,
"created_at": "2021-05-23T03:41:49.015+07:00",
"updated_at": "2021-05-23T12:54:30.580+07:00",
"state": "complete",
"open_signup": false,
"notify_users_when_the_tournament_ends": true,
"progress_meter": 100,
"quick_advance": false,
"hold_third_place_match": false,
"pts_for_game_win": "0.0",
"pts_for_game_tie": "0.0",
"pts_for_match_win": "1.0",
"pts_for_match_tie": "0.5",
"pts_for_bye": "1.0",
"swiss_rounds": 0,
"private": false,
"ranked_by": "match wins",
"show_rounds": true,
"hide_forum": false,
"sequential_pairings": false,
"accept_attachments": false,
"rr_pts_for_game_win": "0.0",
"rr_pts_for_game_tie": "0.0",
"rr_pts_for_match_win": "1.0",
"rr_pts_for_match_tie": "0.5",
"created_by_api": false,
"credit_capped": false,
"category": null,
"hide_seeds": false,
"prediction_method": 0,
"predictions_opened_at": null,
"anonymous_voting": false,
"max_predictions_per_user": 1,
"signup_cap": null,
"game_id": 773,
"participants_count": 24,
"group_stages_enabled": false,
"allow_participant_match_reporting": false,
"teams": false,
"check_in_duration": null,
"start_at": null,
"started_checking_in_at": null,
"tie_breaks": [
"match wins vs tied",
"game wins",
"points scored"
],
"locked_at": null,
"event_id": null,
"public_predictions_before_start_time": false,
"ranked": false,
"grand_finals_modifier": null,
"predict_the_losers_bracket": false,
"spam": null,
"ham": null,
"rr_iterations": 1,
"tournament_registration_id": null,
"donation_contest_enabled": null,
"mandatory_donation": null,
"non_elimination_tournament_data": {
"participants_per_match": ""
},
"auto_assign_stations": null,
"only_start_matches_with_stations": null,
"registration_fee": "0.0",
"registration_type": "free",
"split_participants": false,
"allowed_regions": [
],
"show_participant_country": null,
"program_id": null,
"program_classification_ids_allowed": null,
"team_size_range": null,
"toxic": null,
"description_source": "",
"subdomain": null,
"full_challonge_url": "https://challonge.com/BnkSat0522",
"live_image_url": "https://challonge.com/BnkSat0522.svg",
"sign_up_url": null,
"review_before_finalizing": true,
"accepting_predictions": false,
"participants_locked": true,
"game_name": "8-ball",
"participants_swappable": false,
"team_convertable": false,
"group_stages_were_started": false
}
},
{
"tournament": {
"id": 9845539,
"name": "2021/05/24 Monday Night 10-Ball",
"url": "20210524",
"description": "",
"tournament_type": "double elimination",
"started_at": "2021-05-25T06:34:46.053+07:00",
"completed_at": "2021-05-25T10:54:03.406+07:00",
"require_score_agreement": false,
"notify_users_when_matches_open": true,
"created_at": "2021-05-25T04:01:56.922+07:00",
"updated_at": "2021-05-25T10:54:03.589+07:00",
"state": "complete",
"open_signup": false,
"notify_users_when_the_tournament_ends": true,
"progress_meter": 100,
"quick_advance": false,
"hold_third_place_match": false,
"pts_for_game_win": "0.0",
"pts_for_game_tie": "0.0",
"pts_for_match_win": "1.0",
"pts_for_match_tie": "0.5",
"pts_for_bye": "1.0",
"swiss_rounds": 0,
"private": false,
"ranked_by": "match wins",
"show_rounds": true,
"hide_forum": false,
"sequential_pairings": false,
"accept_attachments": false,
"rr_pts_for_game_win": "0.0",
"rr_pts_for_game_tie": "0.0",
"rr_pts_for_match_win": "1.0",
"rr_pts_for_match_tie": "0.5",
"created_by_api": false,
"credit_capped": false,
"category": null,
"hide_seeds": false,
"prediction_method": 0,
"predictions_opened_at": null,
"anonymous_voting": false,
"max_predictions_per_user": 1,
"signup_cap": null,
"game_id": 6341,
"participants_count": 22,
"group_stages_enabled": false,
"allow_participant_match_reporting": true,
"teams": false,
"check_in_duration": null,
"start_at": null,
"started_checking_in_at": null,
"tie_breaks": [
"match wins vs tied",
"game wins",
"points scored"
],
"locked_at": null,
"event_id": null,
"public_predictions_before_start_time": false,
"ranked": false,
"grand_finals_modifier": null,
"predict_the_losers_bracket": false,
"spam": null,
"ham": null,
"rr_iterations": 1,
"tournament_registration_id": null,
"donation_contest_enabled": null,
"mandatory_donation": null,
"non_elimination_tournament_data": {
"participants_per_match": ""
},
"auto_assign_stations": false,
"only_start_matches_with_stations": false,
"registration_fee": "0.0",
"registration_type": "free",
"split_participants": false,
"allowed_regions": [
],
"show_participant_country": null,
"program_id": null,
"program_classification_ids_allowed": null,
"team_size_range": null,
"toxic": null,
"description_source": "",
"subdomain": null,
"full_challonge_url": "https://challonge.com/20210524",
"live_image_url": "https://challonge.com/20210524.svg",
"sign_up_url": null,
"review_before_finalizing": true,
"accepting_predictions": false,
"participants_locked": true,
"game_name": "10-Ball",
"participants_swappable": false,
"team_convertable": false,
"group_stages_were_started": false
}
},
{
"tournament": {
"id": 9851001,
"name": "2021/05/26 Wednesday Night 9-Ball",
"url": "20210526",
"description": "",
"tournament_type": "double elimination",
"started_at": "2021-05-26T20:48:53.085+07:00",
"completed_at": null,
"require_score_agreement": false,
"notify_users_when_matches_open": true,
"created_at": "2021-05-26T20:46:47.342+07:00",
"updated_at": "2021-05-26T20:48:53.158+07:00",
"state": "underway",
"open_signup": false,
"notify_users_when_the_tournament_ends": true,
"progress_meter": 0,
"quick_advance": false,
"hold_third_place_match": false,
"pts_for_game_win": "0.0",
"pts_for_game_tie": "0.0",
"pts_for_match_win": "1.0",
"pts_for_match_tie": "0.5",
"pts_for_bye": "1.0",
"swiss_rounds": 0,
"private": false,
"ranked_by": "match wins",
"show_rounds": true,
"hide_forum": true,
"sequential_pairings": false,
"accept_attachments": false,
"rr_pts_for_game_win": "0.0",
"rr_pts_for_game_tie": "0.0",
"rr_pts_for_match_win": "1.0",
"rr_pts_for_match_tie": "0.5",
"created_by_api": false,
"credit_capped": false,
"category": null,
"hide_seeds": false,
"prediction_method": 0,
"predictions_opened_at": null,
"anonymous_voting": false,
"max_predictions_per_user": 1,
"signup_cap": null,
"game_id": 485,
"participants_count": 2,
"group_stages_enabled": false,
"allow_participant_match_reporting": false,
"teams": false,
"check_in_duration": null,
"start_at": null,
"started_checking_in_at": null,
"tie_breaks": [
"match wins vs tied",
"game wins",
"points scored"
],
"locked_at": null,
"event_id": null,
"public_predictions_before_start_time": false,
"ranked": false,
"grand_finals_modifier": null,
"predict_the_losers_bracket": false,
"spam": null,
"ham": null,
"rr_iterations": 1,
"tournament_registration_id": null,
"donation_contest_enabled": null,
"mandatory_donation": null,
"non_elimination_tournament_data": {
"participants_per_match": ""
},
"auto_assign_stations": null,
"only_start_matches_with_stations": null,
"registration_fee": "0.0",
"registration_type": "free",
"split_participants": false,
"allowed_regions": [
],
"show_participant_country": null,
"program_id": null,
"program_classification_ids_allowed": null,
"team_size_range": null,
"toxic": null,
"description_source": "",
"subdomain": null,
"full_challonge_url": "https://challonge.com/20210526",
"live_image_url": "https://challonge.com/20210526.svg",
"sign_up_url": null,
"review_before_finalizing": true,
"accepting_predictions": false,
"participants_locked": true,
"game_name": "9-ball",
"participants_swappable": false,
"team_convertable": false,
"group_stages_were_started": false
}
}
]
Where I am trying to grab a tournament that the state is "underway" and return "url" that can then be used to launch a complete URL as described above.
I've created the following:
<?php
$apikey = 'MyAPIKEY';
$contents_api = fopen("https://api.challonge.com/v1/tournaments.json?
state=all&api_key=$apikey", "r");
$json = stream_get_contents($contents_api);
$jsonData = json_decode($json, TRUE);
print $jsonData[count($jsonData)-1]['tournament']['url'];
?>
Now I need to figure out how to grab this information and load the page!!!!
Again, I know this is probably not the best way to ask however, any guidance pointing me in the correct direction would be very helpful.
I was able to get what I wanted using:
<?php
$page = $_SERVER['PHP_SELF'];
$sec = "10";
$apikey = 'MYAPIKEY';
$contents_api = fopen("https://api.challonge.com/v1/tournaments.json?state=all&api_key=$apikey", "r");
$json = stream_get_contents($contents_api);
$jsonData = json_decode($json, TRUE);
//print $jsonData[count($jsonData)-1]['tournament']['url'];
$inputvalue = $jsonData[count($jsonData)-1]['tournament']['url'];
$url= "http://challonge.com/$inputvalue/module?selected-round-filter=2&show_final_results=0&multiplier=2&show_tournament_name=1&scale_to_fit=1"
?>
<html>
<head>
<script>
location.replace("<?php echo $url; ?>");
</script>
<meta http-equiv="refresh" content="<?php echo $sec ?>;URL='<?php echo $page?>'">
</head>
</html>
Related
API failing on brave browser but working in chrome and microsoft Edge
In the beginning luckyOrange is sending some request to the API: https://settings.luckyorange.net to fetch some content. The actual Request URL for this API, which is being shown in other browsers except brave, in the network tab is: https://settings.luckyorange.net/?u=http%3A%2F%2Flocalhost%3A5000%2F-84.540584%2C39.136547%2C9%3Fq&s=153484 This API is working on the chrome and microsoft edge but not on brave. In the Brave Browser's console, I am having this response: GET https://d10lpsik1i8c69.cloudfront.net/w.js net::ERR_BLOCKED_BY_CLIENT -84.540584,39.136547,9?q:9 I have tried: Allowing everything in the 'Site Settings' which is in the URL bar. Debugging my application for any other blockers, none. Also, When hitting that API directly from another tab, it is giving me the response in all browsers (including brave): { "masterID": "181739", "only_enhanced": false, "offline_form": false, "log_console": true, "idle_timeout_mins": 10, "hubspot": false, "ga_events": false, "adobe_dtm_events": false, "addons": { "powered_by": false, "white_label": false, "beta": false, "store_resources": false, "gcs": true, "rdc": true }, "big_dom": true, "keys": false, "hash_changes": false, "anon_ip": false, "polyfill": false, "newTracking": false, "throttled": 0, "offset_bottom": "0", "chat_align": "right", "text_dir": "ltr", "colors": { "chat_bg": "#000000", "chat_title": "#ffffff", "chat_subtitle": "#999999", "chat_border": "#ffffff", "chat_show_blinker": "1", "is_chat_bg_light": false }, "words": { "available_for_chat": "", "offline_message": "", "extra_msg": "", "pre_chat_ask_enabled": false, "pre1": "Enter Your Name", "pre2": "Enter Your Email", "pre3": "", "pre1_r": false, "pre2_r": false, "pre3_r": false, "pre1_t": "text", "pre2_t": "email", "pre3_t": "text", "btn_yes": "Yes, please.", "btn_no": "No thanks.", "btn_stop": "Stop asking me.", "btn_lbl": "chat", "enter_placeholder": "Type here and press <enter> to chat.", "you": "you", "confirm_close": "Are you sure you want to close this chat session?", "paging_operator": "One moment, we're paging an agent...", "composing": "is typing...", "idle": "is idle.", "away": "is away from their keyboard.", "closed": "ended the chat." }, "bc_events": false, "never_chat": false, "scramble": false, "dis_mo_chat": false, "do_not_record": false, "extreme_privacy": false, "ga_polls": "0", "ga_chat": "0", "dom_ready": false, "ip": "157.39.8.146", "fc": true, "site_id": 153484, "access_token": null, "polls": [], "invites": [], "tags": ["Quest Panel"], "auto": false, "now": 1665482096, "now_ms": 1665482096676, "t": 75.708150863647, "ek": "30", "enable_chat": false }
While the JSON is being received from the backend, the last 2 digits of a long are removed
If I try to get an JSON response from a backend I wrote I get following response which is completely correct: { "status": "ok", "get": { "5b7e4b0b-fc98-4107-ab72-32577440e02e": { "isUser": false, "permissions": { "play": true, "disconnect": true, "debug": false, "color": false, "leaderboard-collect-voice": true, "view-bot-log": false, "command-boobs": false, "embed-builder": false, "clear": false, "admin": false, "skip": true, "w2g": true, "pause": true, "clear-queue": true, "leaderboard": true, "rank-self": true, "rank-other": true, "leaderboard-collect-text": true, "queue": true, "move-to-me": false }, "id": 0 }, "d902f18f-95ad-432c-9ee9-27e63ff6fce1": { "isUser": false, "permissions": { "play": false, "disconnect": false, "debug": false, "color": false, "leaderboard-collect-voice": false, "view-bot-log": false, "command-boobs": true, "embed-builder": false, "clear": false, "admin": false, "skip": false, "w2g": false, "pause": false, "clear-queue": false, "leaderboard": false, "rank-self": false, "rank-other": false, "leaderboard-collect-text": false, "queue": false, "move-to-me": false }, "id": 767965825293746217 } } } But it seems if Chrome tries to get the data it gets in the response from the server the correct data but in the preview and the JavaScript of the site gets an wrong value. I tried to change the value but nothing works. It seems that every time the last 2 digits are replaced by zeros.
It has to do with how javascript is handling numbers. Even stored in a long, your number is still "too big" and can't be represented as a Javascript number. You'd be better off storing it as a string. Check out this Stackoverflow subject for more details. Some people brought up alternative solutions.
drive api -- get email based on public file link
say I have a file link in the format of something like https://drive.google.com/uc?id=1o9rhnAr2GIilfjxPm4Wdl1BlaVP4Gsj1 Is it at all possible to get the email address of the one who uploaded this file, since the link is public? I haven't been able to find anything like this in the docs
File.get request will return all the information about the file including the users email. I have altered it slightly but anyone running this request is going to get your email you might want to scramble that file id :) All you need is an API key to be able to get information about a public file. curl \ 'https://www.googleapis.com/drive/v3/files/1o9rhnAr2GIilfjxPm4Wdl1BlaVP4Gsj1?fields=*&key=[YOUR_API_KEY]' \ --header 'Accept: application/json' \ --compressed response { "kind": "drive#file", "id": "1o9rhnAr2GIilfjxPm4Wdl1BlaVP4Gsj1", "name": "pokemon_terrain.jpg", "mimeType": "image/jpeg", "starred": false, "trashed": false, "explicitlyTrashed": false, "spaces": [ "drive" ], "version": "5", "webContentLink": "https://drive.google.com/uc?id=1o9rhnAr2GIilfjxPm4Wdl1BlaVP4Gsj1&export=download", "webViewLink": "https://drive.google.com/file/d/1o9rhnAr2GIilfjxPm4Wdl1BlaVP4Gsj1/view?usp=drivesdk", "iconLink": "https://drive-thirdparty.googleusercontent.com/16/type/image/jpeg", "hasThumbnail": true, "thumbnailLink": "https://lh3.googleusercontent.com/1ZX-DvVSs70fPta2IAsg8tpYbkRDFeU0p-MVIdZPKY2PAGCGLqCAnXPl3MNMcafYNVfmAe2qips=s220", "thumbnailVersion": "1", "viewedByMe": false, "createdTime": "2019-09-16T09:43:40.107Z", "modifiedTime": "2020-02-13T14:12:57.036Z", "modifiedByMe": false, "owners": [ { "kind": "drive#user", "displayName": "p v", "photoLink": "https://lh3.googleusercontent.com/a-/AOh14GjNKXej3SKi_Rc7VwlULYtsnN_A4uYJsxwoc_FR=s64", "me": false, "permissionId": "15907603398143100492", "emailAddress": "vou.pandev#gmail.com" } ], "lastModifyingUser": { "kind": "drive#user", "displayName": "p v", "photoLink": "https://lh3.googleusercontent.com/a-/AOh14GjNKXej3SKi_Rc7VwlULYtsnN_A4uYJsxwoc_FR=s64", "me": false, "permissionId": "15907603398143100492", "emailAddress": "vourtspandev#gmail.com" }, "shared": true, "ownedByMe": false, "capabilities": { "canAddChildren": false, "canAddMyDriveParent": false, "canChangeCopyRequiresWriterPermission": false, "canChangeViewersCanCopyContent": false, "canComment": false, "canCopy": false, "canDelete": false, "canDownload": true, "canEdit": false, "canListChildren": false, "canModifyContent": false, "canMoveChildrenWithinDrive": false, "canMoveItemIntoTeamDrive": false, "canMoveItemOutOfDrive": false, "canMoveItemWithinDrive": false, "canReadRevisions": false, "canRemoveChildren": false, "canRemoveMyDriveParent": true, "canRename": false, "canShare": false, "canTrash": false, "canUntrash": false }, "viewersCanCopyContent": true, "copyRequiresWriterPermission": false, "writersCanShare": true, "originalFilename": "pokemon_terrain.jpg", "fullFileExtension": "jpg", "fileExtension": "jpg", "md5Checksum": "e7bb0cb361585f3845bd2a11e769c70b", "size": "326467", "quotaBytesUsed": "0", "headRevisionId": "0BwYB7bTd8hGMd3A4WERUVHpuODNDdmM2MlZlNUNGQk9rc2hNPQ", "imageMediaMetadata": { "width": 460, "height": 460, "rotation": 0 } }
Touch in Angular
This is the return data I get from a touch event. Conspicuously missing are any useful touch X/Y coords (https://developer.mozilla.org/en-US/docs/Web/API/TouchEvent/changedTouches). This is a hopelessly generic question, but nonetheless, any ideas? The "event" object passed to the function executed on touch: { "originalEvent": { "isTrusted": true }, "type": "touchstart", "timeStamp": 1450388006795, "jQuery203026962137850932777": true, "which": 0, "view": "$WINDOW", "target": {}, "shiftKey": false, "metaKey": false, "eventPhase": 3, "currentTarget": {}, "ctrlKey": false, "cancelable": true, "bubbles": true, "altKey": false, "delegateTarget": {}, "handleObj": { "type": "touchstart", "origType": "touchstart", "data": null, "guid": 2026, "namespace": "" }, "data": null } Now, this IS in an angular UI modal in canvas, but mouse events work fine. Here is my element btw: link: function(scope, element, attrs, model){ //scope.canvasElem = element[0].children[0].children[0]; scope.canvasElem = angular.element($('.touchScreen'))[0]; scope.ctx = scope.canvasElem.getContext('2d'); Here is an example of how I bind: element.bind('touchstart', scope.touchStart); Edit, and here is a mousedown event object for comparison: { "originalEvent": { "isTrusted": true }, "type": "mousedown", "timeStamp": 1450389131400, "jQuery20309114612976554781": true, "toElement": {}, "screenY": 436, "screenX": 726, "pageY": 375, "pageX": 726, "offsetY": 81, "offsetX": 41, "clientY": 375, "clientX": 726, "buttons": 1, "button": 0, "which": 1, "view": "$WINDOW", "target": {}, "shiftKey": false, "relatedTarget": null, "metaKey": false, "eventPhase": 3, "currentTarget": {}, "ctrlKey": false, "cancelable": true, "bubbles": true, "altKey": false, "delegateTarget": {}, "handleObj": { "type": "mousedown", "origType": "mousedown", "data": null, "guid": 2025, "namespace": "" }, "data": null }
It looks like you are using jQuery, or at least a jQuery-like implementation. jQuery does not copy all the touch event properties to the normalized event wrapper. You can however find them under the originalEvent object though. The originalEvent property contains the native touch event, which you can use according to the specification. For example, code like this: $('body').on('touchmove', function(e) { // Access the original event like this: console.log(e.originalEvent); });
Trying to get a deeply embedded object from API object in JavaScript
I am trying to pull out the "quantity" value out of this API call with JavaScript however I cant seem to wrap my mind around it. Does any one feel up for the challenge? { "count": 5, "results": [{ "listing_id": 216653218, "state": "active", "user_id": 57517426, "category_id": 69150359, "title": "Foodie Dice", "description": "Some discription.", "creation_tsz": 1419964059, "ending_tsz": 1430414859, "original_creation_tsz": 1419964059, "last_modified_tsz": 1420033299, "price": "25.00", "currency_code": "USD", "**quantity**": 1, "tags": [], "category_path": ["Geekery"], "category_path_ids": [69150359], "materials": [], "shop_section_id": null, "featured_rank": null, "state_tsz": 1419964059, "url": "https://www.etsy.com/listing/216653218/foodie-dice?utm_source=buddhabar&utm_medium=api&utm_campaign=api", "views": 1, "num_favorers": 0, "shipping_template_id": null, "processing_min": 1, "processing_max": 1, "who_made": "i_did", "is_supply": "false", "when_made": "2010_2015", "is_private": false, "recipient": null, "occasion": null, "style": null, "non_taxable": false, "is_customizable": false, "is_digital": false, "file_data": "", "language": "en-US", "has_variations": false, "used_manufacturer": false, "MainImage": { "listing_image_id": 704444582, "hex_code": null, "red": null, "green": null, "blue": null, "hue": null, "saturation": null, "brightness": null, "is_black_and_white": null, "creation_tsz": null, "listing_id": 216653218, "rank": null, "url_75x75": "https://img0.etsystatic.com/048/0/10392050/il_75x75.704444582_poqv.jpg", "url_170x135": "https://img0.etsystatic.com/048/0/10392050/il_170x135.704444582_poqv.jpg", "url_570xN": "https://img0.etsystatic.com/048/0/10392050/il_570xN.704444582_poqv.jpg", "url_fullxfull": "https://img0.etsystatic.com/048/0/10392050/il_fullxfull.704444582_poqv.jpg", "full_height": null, "full_width": null } },
Use a tool to beautify the output, it helps a lot. One such tool here http://jsbeautifier.org/ As far as your question, you can access it here: data.results[0].quantity