Failing to get simple SoundCloud javascript api method to work - javascript

I have the following code below :
<!DOCTYPE html>
<html>
<head>
<script src="http://connect.soundcloud.com/sdk.js"></script>
<script>
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207",{}, function(user){
console.log("in the function w/ " + user);
});
</script>
</head>
</html>
The code should print the user name to the console however whenever I run this, my console gives the error of :
Failed to load resource: The requested URL was not found on this server:
file://api.soundcloud.com/users/3207?client_id=f520d2d8f80c87079a0dc7d90db9afa9&format=json&_status_code_map%5B302%5D=200
However if I were to directly http://api.soundcloud.com/users/3207.json?client_id=f520d2d8f80c87079a0dc7d90db9afa9, then I get a valid JSON result.
Is there something incorrect with my how I am using the SC.get function?
Thanks

Well, you should test your index.html locally on a web-server like Apache and not by opening it as a file.
Working example
SC.initialize({
client_id: "f520d2d8f80c87079a0dc7d90db9afa9"
});
SC.get("/users/3207", {}, function(user) {
console.log("in the function w/ " + JSON.stringify(user));
var res = document.getElementById("result");
res.innerHTML = JSON.stringify(user);
});
<script src="http://connect.soundcloud.com/sdk.js"></script>
<div id="result"></div>

Related

Unable to Consume Linkedin API through Localhost

I found similar threads but unfortunately didn't help resolve my issue so posting a new thread
I am trying to consume the linked API through localhost. The error I am getting is:
Uncaught Error: You must specify a valid JavaScript API Domain as part of this key's configuration.
Under Javascript Settings, Valid SDK Domains I added
http://127.0.0.1
http://127.0.0.1:8704
http://localhost
http://localhost:8704
http://localhost
I tried adding in https as well but still I am facing the same error.
I tried creating a ASP.NET project in Visual studio and tried running my html file with the associated port number which also I added in valid SDK domain, still the same issue.
My code is below:
<html>
<head>
<script type="text/javascript" src="https://platform.linkedin.com/in.js">
api_key: [MY KEY] //Client ID
onLoad: OnLinkedInFrameworkLoad //Method that will be called on page load
authorize: true
</script>
</head>
<script type="text/javascript">
function OnLinkedInFrameworkLoad() {
console.log('OnLinkedInFrameworkLoad');
IN.Event.on(IN, "auth", OnLinkedInAuth);
}
function OnLinkedInAuth() {
console.log('OnLinkedInAuth');
IN.API.Profile("me").result(ShowProfileData);
}
function ShowProfileData(profiles) {
console.log('ShowProfileData' + profiles);
var member = profiles.values[0];
var id = member.id;
var firstName = member.firstName;
var lastName = member.lastName;
var photo = member.pictureUrl;
var headline = member.headline;
//use information captured above
var stringToBind = "<p>First Name: " + firstName + " <p/><p> Last Name: "
+ lastName + "<p/><p>User ID: " + id + " and Head Line Provided: " + headline
+ "<p/>"
document.getElementById('profiles').innerHTML = stringToBind;
}
</script>
<body>
<div id="profiles"></div>
</body>
</html>

Using JavaScript to get information from BigQuery

I am new to JavaScript and Google BigQuery, so please forgive my ignorance. I am trying to write a javascript to collect data from one of the public databases on BigQuery. I found an answer to this at Obtaining BigQuery data from JavaScript code (the code for which I have pasted below) but when I saved the file as .html, replaced the client id and project number with mine, and tried to run it, I get the Authorize button and the page title. I click the Authorize button, and it disappears, but no query is run. Is there something else I was supposed to replace or is there something else I need to make this work? I saved the file as a .html, perhaps I should have saved it with a different extension?
I tried all three ways of creating a client id in the Google developers console and all gave me the same behavior.
I'm sure its just something silly that I am forgetting, but any advice would be greatly appreciated.
Here is the code given by Ryan Boyd, which I am unable to get working properly(which is surely my fault):
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = '605902584318';
var client_id = '605902584318.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
Update: I opened the Developer Tools in Chrome and found this error in the console:
Failed to execute 'postMessage' on 'DOMWindow': The target origin
provided ('file://') does not match the recipient window's origin
('null')
.
I tried editing in my Google Developer console as per these instructions: Google API in Javascript
Still same error.
Looks like you may need to add:
$('#query_button').show();
to the bottom of the auth() function
like so:
function auth() {
gapi.auth.authorize(config, function()
{
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
$('#query_button').show();
}
Searching for the error you got, I found this page:
Google API in Javascript
Based on the error you're receiving, my guess is that you either do not have your Javascript Origin configured properly on the Google API console you got your Client ID from, and/or you are trying to run your script from the file system instead of through a web server, even one running on localhost. The Google API client, near as I've been able to tell, does not accept authorization requests from the file system or any domain that has not been configured to request authorization under the supplied Client ID. --#citizenslave
It turns out it was a combination of things. I had the Javascript origin not configured properly, I didn't have all the scopes needed for my query, and I couldn't just open the html file in a browser, I needed to create an HTTP server.
So I changed the code to be:
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', {packages: ['geochart']});
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
var config = {
'client_id': client_id,
'scope': 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function(response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function(i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, {width: 556, height: 347, resolution: "provinces", region: "US"});
});
}
function auth() {
gapi.auth.authorize(config, function() {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
I fixed my Google Javascript Origins url to be http://localhost:8888/ and my Redirect uri to be http://localhost:8888/oauth2callback, opened a command prompt to run this command from the directory of my html file:
python -m SimpleHTTPServer 8888
and then went to localhost:8888 in my browser and clicked my html file there.
Thanks so much for all the feedback!
It worked perfectly! Now to change the query for my purposes!

Backbone: passing data to server (save() method, php file)

Hope you can help me with that problem.
I want to use Backbone's save() method and pass to php file data.
But on a very begining I have problem.
In browser's console I execute:
var test = new MyModel(); // - it's ok
test.toJSON(); // - it's ok
test.save(); // and here I have error "TypeError: d.collection is undefined"
When I use localStorage everythink is OK (it's commented in my code below). I can create models, collections, views etc. and operate on them.
I tried to use these tutorials net.tutsplus.com/tutorials/javascript-ajax/understanding-backbone-js-and-the-server/ and http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/ but I can't get how REST works and where I made mistake. Hope you can explain.
index.html
<!DOCTYPE html>
<html>
<head>
<title>S.O.S</title>
</head>
<body>
<h1>Test</h1>
<script src="jquery.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
<script src="backbone.localStorage-min.js" type="text/javascript"></script>
<script >
window.MyModel = Backbone.Model.extend({
defaults: {
title: 'Test'
},
//localStorage: new Store('TEST')
urlRoot: 'api/items'
});
</script>
</body>
</html>
index.php
<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->post('/items', 'addItem');
$app->run();
function addItem() {
$request = Slim::getInstance()->request();
try {
echo json_encode('OK message');
} catch(PDOException $e) {
echo 'Error message';
}
}
?>
folders structure
|->main_folder
|-index.html
|->api
|->index.html
|->Slim
|-> (folder with Slim php library)
Here is a working example http://jsfiddle.net/acDb3/
Even without working REST I didn't got the error you have.
I noticed there is no Content-type for JSON output. You may add this line to the index.php to make it work.
$app->contentType("application/json");
You can also get success and error callacks to see if they are have been called.
test.save(null, {
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});

Exception: missing } in XML expression

I am getting this error Exception: missing } in XML expression and also when i open my html file in FIREFOX and use Firebug 1.9.2, this error appear:
WL is not defined [Break On This Error]
WL.Event.subscribe("auth.login", onLogin);`
Here is my code:
<html><head>
<title>Greeting the User Test page</title>
<script src="js.live.net/v5.0/wl.js" type="text/javascript"></script>
<script type="text/javascript">
var APPLICATION_CLIENT_ID = "id",
REDIRECT_URL = "url";
WL.Event.subscribe("auth.login", onLogin);
WL.init({
client_id: APPLICATION_CLIENT_ID,
redirect_uri: REDIRECT_URL,
scope: "wl.signin",
response_type: "token"
});
WL.ui({
name: "signin",
element: "signInButton",
brand: "skydrive",
type: "connect"
});
function greetUser(session) {
var strGreeting = "";
WL.api(
{
path: "me",
method: "GET"
},
function (response) {
if (!response.error) {
strGreeting = "Hi, " + response.first_name + "!";
document.getElementById("greeting").innerHTML = strGreeting;
}
});
}
function onLogin() {
var session = WL.getSession();
if (session) {
greetUser(session);
}
}
</script>
</head>
<body>
<p>Connect to display a welcome greeting.</p>
<div id="greeting"></div>
<div id="signInButton"></div>
</body>
</html>
I dont know where is mistake, i just copy this sample code from skydrive api tutorial.
Of course, that I id and url strings replace with strings of my personal app.
Thanks for answers.
You need to include the Javascript file from the Microsoft server:
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
Your first <script> tag should look like:
<script src="http://js.live.net/v5.0/wl.js" type="text/javascript"></script>
or possibly
<script src="//js.live.net/v5.0/wl.js" type="text/javascript"></script>
if that site is configured properly. Without that, your URL was interpreted as being relative to the URL of your page.

NowJS error! I can't get the example to work!

I was following along the tutorial at http://nowjs.com/doc when I encountered some errors.
<html>
<head>
<title>index.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
<script src="http://localhost:8080/NowJS/now.js"></script>
<script>
$(document).ready(function(){
var name = prompt("what is your name?","");
now.receiveMessage = function(name,message){
alert(name+" "+message);
};
$('.butt').click(function(){
alert($('#put').val());
now.distributeMessage(name,$('#put').val());
$('#put').val('');
});
});
</script>
and for the server:
var fs = require('fs');
var sys = require('sys');
var server = require('http').createServer(function(req,response){
fs.readFile('index.html',function(err,data){
response.writeHead(200);
response.write(data);
response.end();
});
});
server.listen(8080);
sys.print('woot');
var everyone = require('now').initialize(server);
everyone.now.distributeMessage = function(name, message){
sys.print(name+" "+message);
everyone.now.receiveMessage(name,message);
};
I highly suspect it has something to do with my tag since there isnt anything at /NowJS/now.js.
Can someone enlighten me on this part:
On pages that you would like to use NowJS on, simply include this script tag in your HTML head: NowJS only works on pages that are served through the same http server instance that was passed into the initialize function above.
Thanks for your time.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
script tags can't be self-closed.
In the docs the path in the script tag is lower-case, /nowjs/now.js, whereas in your snippet it is /NowJS/now.js, and so I guess this is the reason it doesn't work.

Categories

Resources