I'm relatively new to API's right now. I'm trying to allow a user to search for a youtube video and have it display the first three results. Refer to code below (I have used the youtube video "Using the Youtube API to search for videos" - FSquare for assistance and give them credit -- there are some modifications and it is not the exact same; it was merely used to help me understand how the API works) :
HTML
(index.html)
<!DOCTYPE html>
<html data-ng-app="myApp">
<head>
<title>Youtube API</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" />
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.js"></script>
<script src="1.4.8.angular.min.js"></script>
<script src="3.1.1.jquery.min.js"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad"></script>
<script type="text/javascript" src="script.js"></script>
<script src="app.js"></script>
</head>
<body>
<header>
<h1>Youtube Viral Search</h1>
</header>
<section>
<form action="#">
<input type="text" id="searchText" placeholder="Search Video...">
<input type="submit" id="searchButton" value="search">
<p id="response"></p>
</form>
</section>
</body>
</html>
JS
(Note: ApiKey is defined as a variable in my code; I am choosing not to showcase it)
$(document).ready(function() {
$(function() {
$("form").on("submit", function(e) {
e.preventDefault();
//prepare request
var request = gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: encodeURIComponent($("#searchText").val()).replace(/%20/g, "+"),
maxResults: 3,
order: "viewCount",
publishedAfter: "2016-01-01T00:00:00Z" //Will get videos published after midnight, 2015.
});
//execute request
request.execute(function(response) {
console.log(response);
});
});
});
function init() {
gapi.client.setApiKey(ApiKey);
gapi.client.load("youtube", "v3", function() {
alert("The Youtube API is ready! Use away.");
});
}
})
For now I want to see what results look like in the console. However, when I run it on a simple Python HTTP Server, the following error results in the console:
Uncaught DOMException: Failed to read the 'contentDocument' property from 'HTMLIFrameElement': Blocked a frame with origin "http://127.0.0.1:8000" from accessing a cross-origin frame.
at contents (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:2:5154)
at Function.map (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:1:14862)
at ot.fn.init.ot.fn.(anonymous function) [as contents] (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:2:5271)
at HTMLIFrameElement.eval (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/components/ActivityMonitor/views/overlay/ActivityMonitorOverlayView.js:1:1894)
at Function.each (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:1:14059)
at ot.fn.init.each (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/vendor/jquery.min.js:1:11922)
at e.bindActivityDetectors (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/components/ActivityMonitor/views/overlay/ActivityMonitorOverlayView.js:1:1853)
at e.init (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/components/ActivityMonitor/ActivityMonitorController.js:1:255)
at onLoaded (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/content.js:1:979)
at eval (chrome-extension://laankejkbhbdhmipfmgcngdelahlfoji/core/ComponentFactory.js:1:943)
From research, it appears that I need to run this on an HTTPS server to see my results, but am unclear on how to do this or if that is the reason.
Related
I am trying to implement Looper theme to my blazor server-side app, and I have the javascript libraries referenced at the end of the in _Host.cshtml.However some scripts in theme.min.js is not running. Why?
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script src="_framework/blazor.server.js"></script>
My problem is that while
<div data-toggle="drowndown"></div> works, but hamburger menu toggle
<button class="hamburger hamburger-squeeze mr-2" type="button" data-toggle="aside-menu" aria-label="toggle aside menu"><span class="hamburger-box"><span class="hamburger-inner"></span></span></button>
does not work. What am I missing here? What am I doing wrong? My theme change script also isn't running. If I step through theme.js and I can see that this script runs when blazor is not active (commenting out blazor.js) but with blazor active, this script does not run.
(line 610) in /library/javascript/theme.js
}, {
key: "toggleAside",
value: function toggleAside() {
var _this4 = this;
var $trigger = $('[data-toggle="aside"]');
$trigger.on('click', function () {
var isShown = $('.app-aside').hasClass('show');
$trigger.toggleClass('active', !isShown);
if (isShown) _this4.hideAside();else _this4.showAside();
});
}
My educated guess is that theme.js is using something that blazor does not allow? Is anybody experienced enough with Looper theme (or with javascript in general) to know why it wouldn't work? Particularly the hamburger toggle and the theme switching code
(line 1992 in /library/javascript/theme.js)
var Looper = function () {
var Looper = new Theme(); // toggle skin thought button
$('[data-toggle="skin"]').on('click', function (e) {
e.preventDefault();
var skin = Looper.skin === 'dark' ? 'default' : 'dark';
Looper.setSkin(skin); // we need to refresh our page after change the skin
location.reload();
}).each(function () {
var isDarkSkin = Looper.skin === 'dark';
var $icon = $(this).find('.fa-moon');
if (isDarkSkin) {
$icon.addClass('far');
$icon.removeClass('fas');
}
}); // make it global
return Looper;
}();
This is the website https://worshipground.azurewebsites.net/ You can use the inspector tool to see that blazor has been correctly loaded and all the javascript files are loaded in /library/javascript and /library/vendor/...
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- End Required meta tags -->
<title> Starter Template | Looper - Bootstrap 4 Admin Theme </title>
<base href="~/" />
<meta name="theme-color" content="#3063A0">
<link rel="apple-touch-icon" sizes="144x144" href="Library/apple-touch-icon.png">
<link rel="shortcut icon" href="Library/favicon.ico">
<link href="https://fonts.googleapis.com/css?family=Fira+Sans:400,500,600" rel="stylesheet">
<link rel="stylesheet" href="/Library/vendor/open-iconic/font/css/open-iconic-bootstrap.min.css">
<link rel="stylesheet" href="/Library/vendor/fontawesome/fontawesome-free/css/all.min.css">
<link rel="stylesheet" href="/Library/stylesheets/theme.min.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/theme-dark.min.css" data-skin="dark">
<link rel="stylesheet" href="/Library/stylesheets/custom-app.css">
<link rel="stylesheet" href="/Library/stylesheets/custom.css" data-skin="default">
<link rel="stylesheet" href="/Library/stylesheets/custom-dark.css" data-skin="dark">
<script>
var skin = localStorage.getItem('skin') || 'default';
var isCompact = JSON.parse(localStorage.getItem('hasCompactMenu'));
var disabledSkinStylesheet = document.querySelector('link[data-skin]:not([data-skin="' + skin + '"])');
// Disable unused skin immediately
disabledSkinStylesheet.setAttribute('rel', '');
disabledSkinStylesheet.setAttribute('disabled', true);
// add flag class to html immediately
if (isCompact == true) document.querySelector('html').classList.add('preparing-compact-menu');
</script>
</head>
<body>
<component type="typeof(App)" render-mode="ServerPrerendered" />
<div id="blazor-error-ui">
<environment include="Staging,Production">
An error has occurred. This application may no longer respond until reloaded.
</environment>
<environment include="Development">
An unhandled exception has occurred. See browser dev tools for details.
</environment>
Reload
<a class="dismiss">🗙</a>
</div>
<script src="/Library/vendor/jquery/jquery.min.js"></script>
<script src="/Library/vendor/popper.js/umd/popper.min.js"></script>
<script src="/Library/vendor/bootstrap/js/bootstrap.min.js"></script>
<script src="/Library/vendor/pace-progress/pace.min.js"></script>
<script src="/Library/vendor/stacked-menu/js/stacked-menu.min.js"></script>
<script src="/Library/vendor/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Library/javascript/theme.min.js"></script>
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
<script src="_framework/blazor.server.js"></script>
</body>
</html>
You may find you have your work cut out in terms of making a JavaScript heavy template work nicely in Blazor.
You will probably need to utilise IJSRuntime
https://learn.microsoft.com/en-us/aspnet/core/blazor/call-javascript-from-dotnet?view=aspnetcore-5.0
I think I know where this problem comes from! If you comment out the following code on the "Host.cshtml" file, this problem will most likely go away!
<script>
Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
</script>
But!!!! You will get some javascript errors related to "WebSocket" instead! something like this:
"WebSocket is not in the OPEN state"
Or
"Uncaught (in promise) Error: Cannot send data if the connection is not in the 'Connected' State."
The cause of these errors is a conflict between "pace.min.js" file and "blazor.server.js" file! You can check this link for more information and get more help
I am trying to write a short code to capture the signature via a tablet screen on a webpage. However, I can't get the area up that captures that signature.
The code I am using, which I have borrowed from other places that do work is:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Simon's Timesheet Signature Capture Test Page</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/south-street/jquery-ui.css" rel="stylesheet">
<link href="/usr/share/javascript/jquery/jquery.signature.css" rel="stylesheet">
<style>
body > iframe { display: none; }
.kbw-signature { width: 400px; height: 200px; }
</style>
<!--[if IE]>
<script src="js/excanvas.js"></script>
<![endif]-->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="/usr/share/javascript/jquery/jquery.signature.js"></script>
<script>
$(function() {
$('#sig').signature();
$('#clear').click(function() {
$('#sig').signature('clear');
});
$('#json').click(function() {
alert($('#sig').signature('toJSON'));
});
$('#svg').click(function() {
alert($('#sig').signature('toSVG'));
});
});
</script>
</head>
<body>
<h1>jQuery UI Signature Basics v18.5.2018</h1>
<p>This page demonstrates the very basics of the
jQuery UI Signature plugin.
It contains the minimum requirements for using the plugin and
can be used as the basis for your own experimentation.</p>
<p>For more detail see the documentation reference page.</p>
<p>Default signature:</p>
<div id="sig"></div>
<p style="clear: both;"><button id="clear">Clear</button>
<button id="json">To JSON</button> <button id="svg">To SVG</button></p>
</body>
</html>
I suspect it has something to do with the links to jquery, unless somebody can see something else glaringly obvious. (I am quite new to this)
Is anyone able to put me in the right direction?
Thanks.
Try this ...
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
<title>Simon's Timesheet Signature Capture Test Page</title>
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/south-street/jquery-ui.css"
rel="stylesheet">
<link href="../js/jquery.signature.css" rel="stylesheet">
<style>
body > iframe {
display: none;
}
.kbw-signature {
width: 400px;
height: 200px;
}
</style>
<!--[if IE]>
<script src="../js/excanvas.js"></script>
<![endif]-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script src="../js/jquery.signature.js"></script>
<script src="../js/jquery.ui.touch-punch.min.js"></script>
</head>
<body>
<h1>jQuery UI Signature Basics v18.5.2018</h1>
<p>This page demonstrates the very basics of the
jQuery UI Signature plugin.
It contains the minimum requirements for using the plugin and
can be used as the basis for your own experimentation.</p>
<p>For more detail see the documentation reference page.</p>
<p>Default signature:</p>
<div id="sig"></div>
<p style="clear: both;">
<button id="clear">Clear</button>
<button id="json">To JSON</button>
<button id="svg">To SVG</button>
</p>
<script>
$(document).ready(function () {
$('#sig').signature();
$('#clear').click(function () {
$('#sig').signature('clear');
});
$('#json').click(function () {
alert($('#sig').signature('toJSON'));
});
$('#svg').click(function () {
alert($('#sig').signature('toSVG'));
});
});
</script>
</body>
</html>
There's a couple of things. I've changed the googleapi call to https instead of http. This helps with browsers that are tetchy with mixed content.
The code for the signature is now also at the bottom, so this should make sure the #sig div is there before the code that attaches itself to it is. This is also helped by the document ready function.
Ignore my ../js/ for the signatures. That's just where I put it. See my comment above about viewing page source to see if the file is actually available.
I know this sounds like a ridiculously simple question, but there is a lot more to it than just a basic function call. I'm implementing authentication on a webapp using the Auth0 python example, they have a full example available here.
I completely understand the python Auth0 stuff, and can get all the details I require from the session, but I simply can NOT work out how to move this sample code in to my app using a simple "login" and "logout" button! The HTML from the sample app looks like this:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome from BootstrapCDN -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
<script src="/public/app.js"> </script>
<link href="/public/app.css" rel="stylesheet">
</head>
<body class="home">
<div class="container">
<div class="login-page clearfix">
<div class="login-box auth0-box before">
<img src="https://i.cloudup.com/StzWWrY34s.png" />
<h3>Auth0 Example</h3>
<p>Zero friction identity infrastructure, built for developers</p>
<a class="btn btn-primary btn-lg btn-login btn-block">SignIn</a>
</div>
</div>
</div>
</body>
</html>
The Javascript that is running is contained in a seperate file that is read in on document load:
$(document).ready(function() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
$('.btn-login').click(function(e) {
e.preventDefault();
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
});
$('.btn-logout').click(function(e) {
e.preventDefault();
window.location.href = '/logout';
})
});
I don't want to use the standard HTML provided with the sample, all I want is a simple "login" button to, well log in the user, but for the life of me I simple don't understand how to make that happen. I want this to be as simple as possible, with all the javascript embedded in the page. I've tried the following, but it fails as the variable "e" is undefined, and I don't understand where it came from in the original example!
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
<p><button onclick="loginfunc()">Click me</button></p>
<script>
$(document).ready(function() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
},
</script>
<script>
function loginfunc(e) {
e.preventDefault();
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
}
</script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- font awesome from BootstrapCDN -->
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
<script src="/public/app.js"> </script>
<link href="/public/app.css" rel="stylesheet">
</head>
<body class="home">
<div class="container">
<div class="login-page clearfix">
<div class="login-box auth0-box before">
<img src="https://i.cloudup.com/StzWWrY34s.png" />
<h3>Auth0 Example</h3>
<p>Zero friction identity infrastructure, built for developers</p>
<a class="btn btn-primary btn-lg btn-login btn-block">SignIn</a>
</div>
</div>
</div>
</body>
</html>
I'm guessing lines 6 and 7 of the original HTML is where all the "magic" is happening, I just don't know how to "read" what's going on there.
<script type="text/javascript" src="//use.typekit.net/iws6ohy.js"></script>
<script type="text/javascript">try{Typekit.load();}catch(e){}</script>
I understand this is a horrible, horrible question, but I've been looking at this for hours now and I'm just ready to give up, I can't look at it any more. For the life of me I don't understand why Auth0 didn't just make a super simple, all-on-on-page example that anyone can understand, not all this fancy bootstrap/css/html mess!
If anyone can help, I will be eternally grateful!
Thank you.
I did it!!!
So it turns out I was waaaaay off, it had nothing to do with the script lines I was focusing on. Here is the working code:
<html>
<head>
<script src="http://code.jquery.com/jquery-3.1.0.min.js" type="text/javascript"></script>
<script src="https://cdn.auth0.com/js/auth0/8.6.0/auth0.min.js"></script>
<script>
function loginfunc() {
var auth = new auth0.WebAuth({
domain: AUTH0_DOMAIN,
clientID: AUTH0_CLIENT_ID
});
auth.authorize({
audience: 'https://'+AUTH0_DOMAIN+'/userinfo', // you can also set this on the .env file and put API_AUDIENCE instead
scope: 'openid profile',
responseType: 'code',
redirectUri: AUTH0_CALLBACK_URL
});
}
</script>
<script>
var AUTH0_CLIENT_ID = '{{env.AUTH0_CLIENT_ID}}';
var AUTH0_DOMAIN = '{{env.AUTH0_DOMAIN}}';
var AUTH0_CALLBACK_URL = '{{env.AUTH0_CALLBACK_URL if env.AUTH0_CALLBACK_URL else "http://localhost:3000/callback" }}';
var API_AUDIENCE = '{{env.API_IDENTIFIER}}';
</script>
</head>
<body >
<p><button onclick="loginfunc()">Click me</button></p>
</body>
</html>
Basically I just pulled the app.js code in to the main html file, then used a standard "onclick" button action to call the auth function. This is so much easier to read than the auth0 example.
I hope this makes the example clearer for someone else in the future. I find it really frustrating the developers confuse the core code example with completely unnecessary css and artys html formatting.
Overflow!
I'm currently working on a little application I have to finish for school monday. I didn't have a lot of time to make something big. So I decided, why not retrieve information of Steam's Web Api and get the stats of players.
The url to the steam api:
http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=76561198263871727
The last parameter &steamid= represents the id of the player. Now I have found out how to get the steamid into a variable, but when trying to add the id to the rest of the url (http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=id should be here and fetching the data with the Ajax.getJson method.. It just doesn't work.. I'm for very experienced with JSON btw.. Can someone help me out with this?
My Web Page:
<!DOCTYPE html>
<html lang="en">
<head>
<!--Meta Information-->
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--JQuery Mobile-->
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css" />
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<!--FontAwesome-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<!--Custom Styles-->
<link href="css/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div data-role="page" id="index">
<div data-role="header">
<h1>CS:GO Stats</h1>
</div>
<div data-role="main" class="ui-content">
<div class="search">
<label for="search">Enter SteamID:</label>
<input type="search" name="search" id="inputSearch" />
<input type="submit" id="butSearch" data-inline="true" value="Search SteamID">
</div>
<div id="result">
</div>
</div>
</div>
<!--getSteamUserId function-->
<script src="js/getSteamUserId.js"></script>
</body>
</html>
My Javascript Code:
$(document).ready(function() {
$('#butSearch').click(function(event) {
var input = $('#inputSearch').val();
$.getJSON( "http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=" + input, function( data ) {
var items = [];
$.each( data, function( key, val ) {
items.push( "<li id='" + key + "'>" + val + "</li>" );
});
$( "<ul/>", {
"class": "my-new-list",
html: items.join( "" )
}).appendTo( "#result" );
});
})
})
Now what I want is to get the stats data from the JSON file into my web page. Would anyone know how to do this? I can also see the JSON is not only a flat JSON file.. Like it has different layers (if that's a good explenation)..
Thanks in advance!
Work with jsonP like here:
$.ajax({
url: url,
dataType: 'JSONP',
type: 'GET',
jsonp: 'jsonp',
success: handler
});
Working example here
I'm not entirely sure about the first part. It gives me an error which after googling led me to "No 'Access-Control-Allow-Origin' header is present on the requested resource" which advises using CORS. Error:
XMLHttpRequest cannot load http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=DA697BB2D106697D5F8AC7E7A2BFAC52&steamid=&76561198263871727. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 400.
Once you have the JSON it's easier. If it's stringified you can turn it into a javascript object with
steamObject = JSON.parse(steamJsonData);
and then navigate through it like a normal javascript object. Cycle through playerstats.stats[i] with a for loop and you can add the data to your page using normal DOM manipulation.
I've been attempting to put together a website that requires obtaining xml data from another website. So far, using only html and javascript (no twitter bootstrap), I can access the website XML and populate a select dropdown menu. Here is the non-bootstrap html code:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
</head>
<body>
<h1>Test App</h1>
<button id="button1">submit</button>
<select id="selectState"></select>
</body>
</html>
and here is the bootstrap html code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Bootstrap CSS-->
<link href="css/bootstrap.min.css" rel="stylesheet" type="text/css">
<!-- jQuery and JavaScript files -->
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/getXML.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<div class="container-fluid">
<div class="row-fluid">
<div class="span4 col-xs-3">
<form class = "well">
<h2 class="page-header">Inputs</h2>
<label class="control-label" for="selectState">Select State:</label>
<select id="selectState"></select>
<button type="submit" class="btn btn-default" id="button1" >submit</button>
</form>
</div>
</div>
</div>
</html>
and here is the getXML.js script:
var HttpClient = function() {
this.get = function(aUrl, aCallback) {
anHttpRequest = new XMLHttpRequest();
anHttpRequest.onreadystatechange = function() {
if (anHttpRequest.readyState == 4 && anHttpRequest.status == 200)
aCallback(anHttpRequest.responseText);
}
anHttpRequest.open( "GET", aUrl, true );
anHttpRequest.send( null );
}
}
$(document).ready(function(){
$( "#button1" ).click(function () {
aClient = new HttpClient();
aClient.get('http://www.waterqualitydata.us/Station/search?characteristicName=Caffeine&mimeType=xml&bBox=-92.8,44.2,-88.9,46', function(data) {
xmlDoc = $.parseXML( data ),
$xml = $( xmlDoc ),
$LocName = $xml.find( "MonitoringLocationName" );
var arr = [];
$.each($LocName,function() {
arr.push( $(this).text() );
});
for ( var i = 0; i < arr.length; i = i + 1 ) {
$('#selectState').append('<option>'+arr[i]+'</option>');
}
alert( "success" );
});
});
});
Now, when I try and using the Twitter bootstrap html, I am getting a Cross-Origin Request Block due to the Same Origin Policy.
Is there any reason why the scripts that don't use Twitter Bootstrap can get around the SOP, while the twitter bootstrap version can't?
Modify the Bootstrap script to include the 'type' attribute, like so:
<script src="js/bootstrap.min.js" type="text/javascript"></script>
The 'type' parameter here is key - it is what allows the remote request to happen. CSS and JS are allowed to do this kind of cross domain linking, as it is judged by the W3C gods to be a low security risk (at least last I checked).
Check these links out for more information on CORS:
IE's explanation: http://msdn.microsoft.com/en-us/library/ie/gg622939%28v=vs.85%29.aspx
Mozilla's thoughts: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy
OK, I think I found the problem. I was placing the <button> inside a <form> element. This apparently raises the SOP block. Without the <form> element, no SOP block was raised.
I haven't looked at the exact reason behind this, but maybe its related to a security feature baked into the <form> element, since <form> elements can be used to pass sensitive information (passwords, etc.)?