Let me start off with saying I just figured out how to use JQuery's "$.ajax()" just a few days ago. I've been able to read local .xml and .json files.
Also, I've figured out how to use the google maps API to import dynamic and static maps. (just following the google documentation)
Now, I had an idea to use steam IDs for a school project, but I keep getting this error:
XMLHttpRequest cannot load http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=[MY_SECRET_KEY]2&steamid=76561197960435530&relationship=friend. Origin http://local.mysite.com is not allowed by Access-Control-Allow-Origin.
(I took out the key, and the generated key is suppose to allow access to http://local.mysite.com)
Here is my code:
<script type="text/javascript">
$.ajax({
url: "http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=[MY_SECRET_KEY]&steamid=76561197960435530&relationship=friend",
dataType: "json",
success: function(data){
console.log(data);
},
error: function(req,text,error){
console.log(text);
console.log(error);
console.log("DIDN'T WORK!")
}
});
</script>
Does anybody know what's going on? I can't seem to get this to work.
See this answer and the posts here. For more background visit mdn.
Essentially you're running into a security issue where the browser won't allow you to make a request from http://local.mysite.com to http://api.steampowered.com.
Do you have access to a server? Instead of making a request like this: browser -> steampowered you can make a request like this browser -> your server -> steampowered.
You're going to want to create an endpoint on your server (so that it's in your domain) that you can send a request to, that will in turn send a request to steam powered.
What language / framework are you running and we can give you example code.
Related
I am new to API usage. I have properly managed to utilize Google Page Insights V.5 API through javascript code, but I cannot for the life of me succeed in doing so for GTMetrix. It seems the only information relating to GTMetrix API & Javascript is a link to the RapidApi website. I simply wish to achieve the same simple retrieval of data from GTMetrix as I have from Google. Is this possible?
Am I simply structuring my request incorrectly when I set it as:
https://gtmetrix.com/api/0.1/?login-user=myemail#email.com&login-pass=MyRanDomApIKeY&location=2&url=https://sitetotest.com
Because when I set my Google Page Insights Request URL as the following it works.
https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=https://websitetotest.com&category=performance&strategy=desktop&key=MyRanDomApIKeY
The below code works for Google Page Insights and I am even able to retrieve JSON data in a browser window with a URL such as:
<div id="firstmetric"></div>
<br>
<div id="domSize"></div>
<button>Click Me</button>
<script>
$('button').click(function(){
var baseUrl = "https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=";
var fieldUrl = "https://websitetotest.com";
var trailing = "&category=performance&strategy=desktop&key=MyRanDomApIKeY";
$.getJSON(baseUrl + fieldUrl + trailing, function(data){
console.log(data);
var item = data.lighthouseResult.categories.performance.auditRefs[0].weight;
var domSize = data.lighthouseResult.audits['dom-size'].displayValue;
$("#firstmetric").html( item );
$("#domSize").html( domSize );
});
});
I truly need it spelled out for me because anything less is going to lead me to ask follow up questions and put us in a tail spin. :/
As a newbie, JSFiddle has been a life saving resource for testing and trying, breaking, and building in my learning process. If it wouldn't be too much to ask for, a fiddle would help me get my brain around things.
The parameters that you are using: login-user and login-pass refer to HTTP authentication on the page you are analyzing (as in, GTmetrix will pass these parameters on your analysis) not your GTmetrix API credentials.
The authentication used for the GTmetrix API is your e-mail for the username and your API key as the password, as pointed out by the API docs.
Another thing to keep in mind is that GTmetrix will not allow you to do API calls through your web application frontend, since they disallow CORS requests. If you do it through your Web application on a normal website, you would be exposing your GTmetrix API key, which is probably not a good idea.
So, you would then do it through your backend code. For example if done through Node JavaScript:
fetch("https://gtmetrix.com/api/0.1/locations", {
headers: new Headers({
"Authorization": 'Basic ' + btoa("[YOUR E-MAIL]" + ":" +"[YOUR API KEY]"),
}),
}).then(res => res.json())
.then(response => console.log(response));
would print me the array of locations.
Note that whichever backend code you choose, you need to add the basic authorization header request for you API call and encode it properly (that is what the btoa function call does).
Background
I simply want to create a landing page that has a form that saves visitors email address in a Google Sheet.
I found this useful post that has a google app script that does the work. I followed the instructions (on my localhost) and here is the request code:
request = $.ajax({
url: "https://script.google.com/macros/s/my_app_script_id/exec",
type: "post",
data: serializedData
});
But when I click on submit I get this error:
XMLHttpRequest cannot load
https://script.google.com/macros/s/my_app_script_id/exec.
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://localhost:8000' is therefore not allowed
access. The response had HTTP status code 405.
Which is kind of weird, considering that I have already published the app to be accessible from everyone as depicted here:
Fair enough, I need to use CORS to access Google APIs.
Problem
The instructions above require that users authenticate themselves, so this is what a user flow would look like on my landing page:
given user adds email in text field
when user clicks on get started button
then
expected
the form should submit just fine
actual
a Google Authentication screen shows up, and asks people to authorize the app
Question
How can I make the web form run the Google App script without?
Update
Interestingly, I tested the same script on the blog post and it works fine, but if I copy the url of the script there https://script.google.com/macros/s/AKfycbzV--xTooSkBLufMs4AnrCTdwZxVNtycTE4JNtaCze2UijXAg8/exec" and call it from my webservice, I get the same CORS error message.
So this is proof that the script can't just be called by anyone, it must be whitelisted somehow. How can I do that?
Update 2
The author of the blog article implied that I should be using https, working on setting that up.
Update 3
I'm using JSONP right now, but somehow the way the google app script interprets the JSONP data is weird.
So as instructed by Spencer Easton I'm calling it like so:
var url = "https://script.google.com/macros/s/AK...g8/exec?data=" + serializedData +"&callback=?";
$.getJSON(url, successCallBack).fail(failCallback)
however I keep on getting undefined,
I tried to debug my Google App script code using instructions from here like so:
function fakeGet() {
var eventObject =
{
"parameter": {
"email": "hindi",
"callback": "fakecallback"
}
}
doGet(eventObject);
}
This code worked perfectly and updated the spreadsheet as expected. So what am I missing here? How is Google App script exactly interpreting the jsonp data?
Since you are returning JSON you have to use JSONP.
https://developers.google.com/apps-script/guides/content#serving_jsonp_in_web_pages
http://ramblings.mcpher.com/Home/excelquirks/gassnips/jsonpnotp
For you it would roughly look like:
postToSheet.js
var url = "https://script.google.com/macros/s/AK...g8/exec?data=" + serializedData +"&callback=?";
$.getJSON(url, successCallBack).fail(failCallback)
code.gs
...
// we'll assume header is in row 1 but you can override with header_row in GET/POST data
var headRow = e.parameter.header_row || 1;
var callback = e.parameter.callback; // required for JSONP
...
return ContentService
.createTextOutput(callback+'('+ JSON.stringify({"result":"success", "row": nextRow})+')')
.setMimeType(ContentService.MimeType.JAVASCRIPT);
I am in quite an interesting situation. I work for a middle sized company and we have IE 11 for our browser but for a particular application I am programming, its document mode is set to IE 5. I am making calls to a web service located within the company Intranet (the particular URL is https) and the website where I'm making the call is http (not sure if I can set document.domain or anything here). I am currently using ajax and I'm able to successfully communicate with service and get code back using the code below. Although, each time I do get the message that says, "the information you're accessing is coming from another source." If I hit yes, then I get information back from the server, if I hit no, then the data does not come through. I tried to call this same method from a different page on the same website, and instead get the access denied error, without even having the prompt. That one really has me confused.
I've read through many many different articles on the subject of CORS at this point and know there's a few things to try to avoid this message. Credentials are omitted below. I am using Jquery 1.9.1 minimized version.
$.support.cors = true;
$.ajax
({
type: "POST",
crossDomain: true,
beforeSend: function(request)
{
request.setRequestHeader("Authorization", "");
return true;
},
url: webServiceURL,
dataType: "xml",
async: true,
data: soapMessage,
contentType: "text/xml; charset=\"utf-8\"",
success: OnSuccess,
error: OnError
});
}
function OnSuccess(data, status)
{
alert(status);
alert(data);
var documentValArr = parseXMLRrec(data);
insertDataIntoTable(documentValArr);
}
function OnError(request, status, error)
{
alert(request.responseText);
alert(error);
alert(status);
}
Enable cross domain sources IE setting. I suppose this can try to be set for that specific URL in that intranet zone, but it still feels wrong to me. Not sure how the security group at work would feel about it either.
Add the URL I'm trying to access to the Intranet trusted sites. I think this would fix the issue I'm seeing and this is something I definitely would want to try.
Also, when testing on my local workstation and calling the web service through IE 11 doc 5 mode, I do not get the message.
Work with the group that owns the server where the service lives, and see if they can somehow add URL's that can access the service alright. This would be interesting because there are quite a lot of production sites.
Because I'm using IE 11 in doc 5 mode I could try to use the XDomainRequest object but I am not sure if it would be a worth while effort to do this if the earlier options work out.
So there my interesting scenario is. I would very much like some feed back from people on the situation, what they would do, and what type of things and solutions go for. THank you very much for all input and ideas!
I'm trying to make an app using phonegap, but what I want to know is if it is possible to store information online. For example, say there is a number variable, and it is added to when a button is pushed. Could that value be saved somewhere and then a totally different device can retrieve the variable?
I looked at databases, but I couldn't really understand it. I want something that can be accessed by any device as long as It has a key or something.
Is this possible? If so, how would I do it?
PhoneGap uses JS so you cannot connect to the database directly. You should create a Web service using server side languages like PHP on external server and make ajax request on your web service. This approach is possible using PhoneGap.
Sample Code will look somewhere near:
function FetchData() {
$.ajax({
async: false,
type: "GET",
url: "Your_WebService_URL",
dataType: "json",
success: function(data) {
$.each(data, function(i, object) {
if(i==="title"){
document.getElementById("title").InnerHTML = object;
}
if(i==="home_image"){
document.getElementById("title").InnerHTML = '<img src="'+object+'"/>';
}
});
},
error: function() {
alert("There was an error loading the feed");
}
});
The web service, in this case json will throw the variables. May me somewhere like this :
[{"title":"my application"},{"home_image":"http://link.com/image.png"}]
I think this article is useful to you: Loading external data into a PhoneGap app using the jQuery JSONP plugin for cross-domain access. Also see this similar question here:
This is entirely possible.
You essentially need two components: the client interface, and the server.
The client displays the results to the users, and, using your example, waits for a button to be pushed. On the push of that button, the client would send a request to the server to increment the stored value (possibly through a jQuery.post, or get, function call).
The server page, written in php for example, receives this request, and accesses a file, or more realistically a database, to increment the value.
With some Googling, this should be very doable, but post specific questions if you get stuck.
I am writing a simple widget that renders a canvas participation graph just like the one's on github.
It uses the data at http://github.com/[user]/[repo]/graphs/participation
The widget works great and is basically done. The only problem I have is when I try to retrieve the json data from the above link via XHR (rather than just copying and pasting into the widget as I have been), I run into the same origin access control problem.
Is there any way I can access this information at all, either via XHR or some hidden github api feature?
I believe Github supports JSONP and CORS through its API. You could also setup a server-side proxy, through which XHR requests are made to a same-origin page which then does a server-side request to Github.
To answer your question about the proxy, yes it's very simple. I had actually done this exact thing about two years ago using Python and Tornado. I realize this isn't PHP, but it reads close enough to english to give you the idea about how it works. This particular proxy was returning a raw gist.
# /proxy/gist
class GetGistHandler(BaseHandler):
def get(self, id, filename):
url = 'http://gist.github.com/raw/%s/%s' % (id, urllib.quote(filename))
resp = urlfetch.fetch(url)
self.finish(resp.content)
It can then be consumed with something along the lines of
$.ajax({
url: '/proxy/gist',
dataType: 'JSON',
data: {
id: $('#id').val(),
filename: $('#filename').val()
},
success: function(json) {
// ...
}
});