Creating an Amazon S3 Bucket using jQuery and REST - javascript

I am wanting to try and do a handful of things with the use of jQuery and Amazons S3 API via REST. My key issue is not being familiar with REST well enough (or not as well as I thought I knew) to know if this approach would even remotely work right. I have tried searching endlessly for some tidbit of an example and came up fruitless, maybe I am searching for the wrong things I don't know, but as a last ditch effort I figured I'd hit up my new favorite place, here..
What I need to do is send. PUT a request to the API to create the bucket. Based on the S3 API docs I came up with
var AWSAccessKeyId = "";
var AWSSecretAccessKey = "";
var AWSDomain = ".s3.amazonaws.com";
function createNewBucket(bucketName)
{
var bucketString = 'HTTP/1.1\n';
bucketString += bucketName + AWSDomain + '\n';
bucketString += 'Content-Length: 0 \n';
bucketString += 'Date: Wed, 01 Mar 2009 12:00:00 GMT \n';
bucketString += 'Authorization: AWS ' + sha1_string;
$.ajax({
url: bucketName + AWSDomain,
type: 'PUT',
data: bucketString,
success: function(data)
{
},
error: ''
});
}
though concept isn't complete with the above I am just starting it out, and I started questioning if this idea of approach was even going to work.. And if it is to work with the above or in any means provided here for help how would I also work with the response to know if it was successful or not? I know if I can nail this one piece down I can handle for the most part the rest of my issues to come. Its just tackling the first hump and figuring out if I am going about it the right way. Its also worth mentioning that I have been tasked with doing this purely javascript style with or without the help of a lib like jquery. I can't use PHP, or the like in this concept. So if anyone can throw me a bone i'd be greatly appreciative.
On a side note, does anyone know if theres a means of actually testing something like this stuff out without actually having a S3 account, cause I can't afford to pay for an account just for the sake of testing let alone any other reason.

Firstly, I am getting the feeling that you are quite new to consuming web-services client side.
It is often best to start with something simple.
If I have a resource that returns a string... say test.html -> "Hello World!"
And the URL for this web-service is some-realy-long-id.s3.amazonaws.com
then we have the following:
$.ajax({
url:'some-realy-long-id.s3.amazonaws.com/test.html',
type: 'PUT',
data: {
'myKey':'myValue'
},
success: function(data) {
//alert dialog containing "Hello World!"
alert(data);
},
error: ''
});
You must remember that requests from the browser follow the same-origin policy, so unless you are planning to use JSOP, or some other cross-domain hack you will run into trouble.
p.s. another little piece of advice is to use right hand braces in Javascript as it performs semi-colon insertion (which will bite you if you return a object literal).
Oh yes and a lot of old browsers do not support 'PUT' which you may need to consider.

Related

How to return a javascript object from php using ajax

I've been on this for hours already, I've read tons of articles and still cant figure it out.
Here's the deal.
I am working with Chrome extensions and I want to do a call to my server that returns me a js object. I dont want to inject this into the page, but I want to be able to use it within my content script.
NOTE: I cannot use eval() (I have tried though) and I cannot use jsonp
I am using a framework so my headers arent set here, but they set to return application-type application/javascript utf-8;
my php side looks like this:
$refererObj = 'var refererObj = {
myFunc: function () {
console.log("hello");
}
};';
echo $refererObj;
my js looks like this
$.ajax({
url: myUrl,
crossDomain: true,
data: postData,
dataType: "json",
type: "POST",
}).done(function(data){
eval(data);
console.log(data);
console.log(refererObj);
});
The first console.log gives ["var refererObj = {↵ getProducts: function () {↵…(products);↵ console.log("hello");↵ }↵};"]
The second gives "Uncaught ReferenceError: refererObj is not defined"
I get the response as a string with the javascript object and everything is all good until I actually want to "convert" the string into a usable code.
Any help would be really great.
Thanks
You actually can use eval() if you relax the default Content Security Policy with unsafe-eval. But it's a big hammer that's best avoided.
You can use JSONP, again, if you can serve it off an https server and add it to script-src of the Content Security Policy. This is slightly less of a security risk.
I doubt there is any other solution: anything you load off an external server is to be considered tainted and if you find a way to execute it - congrats, you just bypassed CSP in Chrome and should go claim your bug bounty.
Please note that in case of simply JSON data it's all moot, you can just load it with XHR and JSON.parse it. But your example contains code.

Cache-Control in node.js http.get

I'm making requests to JSON objects with node using http.get(), it all works fine but, in some cases, I get an outdated version of the page (there's a date field that enables me to make sure). The behaviour is really inconsistent, I can get the right thing one moment, and the wrong thing the next... Here's my request :
var options = {host:'host.com',path:urlPath,headers:{'Cache-Control':'no-cache'}}
http.get(options, function(res){
//JSON.parse result and check the date, sometimes 17/1, sometimes 10/1
});
Is there anything wrong with the request header? I tried 'max-age=0' instead of 'no-cache', to no avail..., does anyone have an idea where this could come from? In my browser, I get the last version all the time, a bit lost here, Help!
Solved it, thanks to users comment, what I did is :
urlPath+="&ie="+(new Date()).getTime();
var options = {host:'host.com',path:urlPath,headers:{'Cache-Control':'no-cache'}}
http.get(options, function(res){
//JSON.parse result and check the date, sometimes 17/1, sometimes 10/1
});
Stupid and awesome at the same time...

Using JSONP API from forecast.io with WinJS

First off, apologies if this is a silly question, I'm new to WinJS and relatively new to Javascript, but I've been going great til I hit this roadblock.
I'm currently working on a weather app for Windows 8 using WinJS, and I'm trying to pull the data from the forecast.io API, which in my case is provided in JSONP format.
I easily got it working in-browser using jQuery and .getJSON, but since I have to use WinJS.xhr to request the data instead I'm having some difficulty.
I can pull the data just fine using the following code:
function getWeather() {
WinJS.xhr({
type: "GET",
url: "https://api.forecast.io/forecast/*ommited API key*/-36.044394,146.953718?callback=?&units=si",
headers: { "Content-type": "application/json" }
}).then(function complete(data) {
var weatherData = data.responseText;
(new Windows.UI.Popups.MessageDialog(weatherData, "Success!")).showAsync().done();
}, function error(data) {
(new Windows.UI.Popups.MessageDialog("Failed.", "Error")).showAsync().done();
});
}
This shows me the data in a popup window, so I'm sure that I've accessed it. The problem is, I can't do anything with it. In jQuery I simply used "data.currently.temperature" to get the current temperature data, but I can't get something similar working in this situation.
Any help or pointers would be greatly appreciated!
P.S sorry if I butchered any terminology, I'm doing my best.
Here's what data.responseText returns, there's quite a lot so I put it in a text file.
http://justadddesign.net/data.responseText.txt
It's because data.responseText is string not object. Try:
var forecastInfo = JSON.parse(data.responseText);
and then access forecastInfo object properties.

Songkick API Using JQuery

I'm having issues gathering data using JSON on the Songkick API. I'm really new to jQuery and Javascript so please forgive me if this looks really crude. I've spent some time trying to research the proper syntax I need but I just keep ending back up at square one.
What im trying to do is make the request using jQuery and then add the results into my HTML in an list. Any help anyone can give me would be fantastic.
Here's what I have so far.
<script>
$.getJSON("http://api.songkick.com/api/3.0/artists/3950031/calendar.json?apikey={apikey}",
function(data){
var events = data['resultsPage']['results']['event'];
for (var i=0;i < events.length; i++) {
$("#events").append('<li>'+events[i]['displayName']+'</li>');
}
});
</script>
Thanks!
sorry i took so long to get back, i left the office about the time you replied last night
here is what I came up with:
$(document).ready(function() {
$.ajax({
url: "http://api.songkick.com/api/3.0/artists/480448/calendar.json?apikey=APIKEY&jsoncallback=?",
dataType: "jsonp", // <== JSON-P request
success: function(data){
$.each(data["resultsPage"]["results"]["event"], function(i, entry){
$("#events").append('<li>'+entry.displayName +'</li>');
});
}
});
});
I think the issue you were having was with JSON, JSON is subject to the same origin policy (which I read about on here ( $.getJSON not working ). Instead you have to use JSON-P adding
&jsoncallback=?
at the end of the URL tells Songkick to send it as a JSON-P request. This was the main issue.
Other issues included minor coding errors: there was an extra ( in your append string, I also used $.Each as appose to a for loop but either would work, hope this helps and you may want to take your API code off if the fix worked :) Just change API Key to your key and it should be fine (i also changed the band to chevelle as the other one had no entries)

Problems using jQuery AJAX to parse XML

I'm not a very experience programmer and have been learning HTML/CSS/JS on the fly. I've been trying to parse XML using jQuery AJAX methods with absolutely no luck.
Here is my code in use: http://jsfiddle.net/Kb5qj/1/
And here is my code in plain sight:
$(document).ready(function() {
var divid = "#xmlcontent"
function parseXML(xml) {
$(divid).empty();
$(xml).find("CD").each(function() {
var artist = $(this).find("ARTIST").text();
var title = $(this).find("TITLE").text();
$(divid).append("<li>" + artist + " - " + title + "</li>");
});
}
function printError() {
$(divid).html("An error occurred");
}
$.ajax({
type: "GET",
url: "www.w3schools.com/ajax/cd_catalog.xml",
dataType: "xml",
success: parseXML,
error: printError
});
});
I don't know what the problem could be. I have written and re-written and copy/pasted that $.ajax call many many times, but no matter what I do nothing ever happens. Help me please?
like I mentioned it will fail on jsfiddle as they dnt actually send the get request. here is the api on how to achieve the same: http://doc.jsfiddle.net/use/echo.html
If you try the same on your local system it will fail probably cos you are making a cross domain request and your browser natively blocks such requests. That is where jsonp comes it to play its to retrieve json data over cross domains..
You can hack it a little to do the same for js.. here is a SO post about the same: Is there an existing tool for jsonp like fetching of xml in jquery?
With a little bit of fudging, everything in the parsing seems to work fine. Check out this JSFiddle.
You can't use get requests from JSFiddle, but I mocked up the XML into HTML. You may want to try placing your XML document into the DOM to help suss your issue.

Categories

Resources