Allow my Tumblr blog's content to be accessed by another page - ajax

I'm attempting to copy all of the actual content from my Tumblr blog using a script I wrote on a different web page, but I'm having a bit of trouble with gaining access to the content. My ajax call is as follows:
$.ajax({
url: "http://solacingsavant.tumblr.com/",
dataType: 'jsonp',
success: function(data) {
var elements = $("<div>").html(data)[0].getElementsByTagName("ul")[0].getElementsByTagName("li");
for(var i = 0; i < elements.length; i++) {
var theText = elements[i].firstChild.nodeValue;
alert(theText); // Alert if I got something
// This is where I'll strip the data for the items I want
}
}
});
but as it is the console gives me an error of "Resource interpreted as Script but transferred with MIME type text/html" which I looked into here and changed the corresponding meta tag in the HTML of my blog to <meta http-equiv="Content-Type" content="application/javascript; charset=utf-8" /> with no success
I also tried using dataType: 'html' (which makes more sense to me) but I was getting a console error of "Origin is not allowed by Access-Control-Allow-Origin" which I also looked into and added a meta tag to my Tumblr blog with <meta Access-Control-Allow-Origin="*" />, but again didn't succeed
Here is a jsFiddle to work with
Does my approach not work because Tumblr as a whole does not allow changes to Access-Control? If so, how might I work around the issue? If not, what am I doing wrong?
MAJOR EDIT (based on mikedidthis's helpful comments)
It seems that I am not able to do this without a Tubmlr API, so I obtained an API key and now have access to the json results that the API sends out. I am able to get a jsonp object using the API key to in the console. My javascript at the moment:
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/info?api_key=APIkeyGoesHeRe",
dataType: 'jsonp',
success: function(results){
console.log(results);
// Get data from posts here
}
});
This SO post was helpful in understanding how I can change data on my Tubmlr page from the source and find out basic information about the site, but not about how to obtain actual data from individual posts. I tried looking through the results object and was unable to find any data related to posts, nor was I able to append the results to the jsfiddle. So my questions now are, "Can I copy data (say the written text in a post) from individual posts using this approach? If so, how? If not, what other approach should I use?"

A really quick answer
The tumblr API documentation really covers using the API well, however, to give you a little start, lets grab all your Text Posts.
First you need to query the API for any of your post that are of the type Text.
The documentation states (http://www.tumblr.com/docs/en/api/v2#posts) that we should use the following url and specifying the type which we you will set to text:
api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts[/type]
And below is an example based on the OP fiddle.
$.ajax({
url: "http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/text?api_key=XXXXXXX",
dataType: 'jsonp',
success: function(data){
posts = data.response.posts
$.each(posts, function(i) {
console.log( posts[i].title, posts[i].body )
});
}
});
So for each query of the API, we will receive back an object. You will need to filter this object to get the data you want from it.
In context of the post queries, you can get directly at your posts using data.response.posts object.
To find out what data is available for each post type, the documentation has it covered: http://www.tumblr.com/docs/en/api/v2#text-posts
To the content for each of the Text post types, you need to loop through the posts object and then grab the value for the key named title and body.
Example here: http://jsfiddle.net/ZpFwL/
Bonus Time
It is possible to get posts for all types, by dropping the type from the URL:
http://api.tumblr.com/v2/blog/solacingsavant.tumblr.com/posts/?api_key=XXXXXXX"
Remember this is a really, quick example and not for the real world.

Related

ASP.Net MVC 3 VB.Net Ajax request gives me a 403 forbidden error

I've been trying to make an Ajax call from my vbhtml page and I can't seem to get it working. I've been researching for a while now my problem but I can't seem to find an answer, maybe it is because I don't actually know exactly what to ask.
In my code i am trying to send the value that was selected in a DataGrid from DataTables.net so that i can retrieve the information related to the selection and put it in some textboxes.
Anyways, I've been getting a 403 frobidden error when doing the ajax
Here's my View code
function ShowInfos(selected) {
$.ajax({
type: "POST",
url: "/Controllers/TelephonieController.vb/Show",
data: '{nomEcran: "' + selected + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
Here's my Controller code
<System.Web.Services.WebMethod()> _
Public Shared Function Show(nomEcran As String) As String
Return "allo"
End Function
(Sorry it's a bit in french)
This is the error it gives me
POST http://localhost:4390/Controllers/TelephonieController.vb/Show 403 (Forbidden)
I've only just started with Web so I might be a total newbie with this, but i have checked on the Web and people have been saying to take out ContenType or DataType and I've done both, I even tried sending and empty String with the Data but I can't seem to get it to work.
A bit off topic sort of, I tried an other way of doign ajax which is exactly this : http://msdn.microsoft.com/en-us/library/dd381533(v=vs.100).aspx?cs-save-lang=1&cs-lang=vb#code-snippet-2
the problem is I can't seem to understand how I should send or could send a javascript variable to the controller.
If someone has a better way of doing things than what I am doing right now feel free to comment so I can learn.
As you are using asp.net mvc3, you can try #Url.Action(...
url: "#Url.Action('Telephony','Show')",
You just need to provide controller and action name. Dont know why are you using TelephonieController.vb in url this isnt web form.
Though i dont have experience in vb, but still feels that vb would work like c#

Uncaught SyntaxError: Unexpected token <, when calling angularJS $http.jsonp

I'm trying to work with the IUCN Red List web services API (here's an example output). Unfortunately I haven't been able to find any documentation other than this one-off Gist. It looks as though the API is constructing an HTML document rather than returning a data object, which isn't something I've experienced in the past. I also notice that in the example there is no mention of a ?callback=JSON_CALLBACK in the URL, which I would expect when dealing with JSONP.
I've constructed an http request in AngularJS like so:
atRiskApp.controller('IucnController', ['$scope', '$routeParams', '$http', function ($scope, $routeParams, $http) {
$scope.iucn = $routeParams.iucn; // pulling a number from the URL: ex. 22718591
$scope.getIUCN = function () {
var iucnUrl = 'http://api.iucnredlist.org/details/' + $scope.iucn + '/0.js';
$http.jsonp( url )
.success( function (response) {
console.log(response);
})
.error( function (response) {
console.log(response);
});
};
}]);
Although the HTML document is being successfully passed to my app I'm getting the following error message:
Uncaught SyntaxError: Unexpected token <
It seems like the app is expecting to get Javascript, and is instead getting an HTML document, which it apparently can't parse. I've tried adding a config object to the request based on the angular docs: $http.jsonp( {url: iucnUrl, responseType: 'text'} ) without any luck.
My question is, how do I work with the returned HTML document, or am I way off track here?
Response from the API is an HTML document with a javascript extension:
On the page you linked to in your comment , I found some potentially useful information under the heading API Index.
You can actually get JSON for all levels of taxonomy, including your example Aneides aeneus. However, this JSON doesn't include all of the data from the HTML version, so it's not as useful. Hopefully this helps a little.
API Index (excerpt)
It is also possible to retrieve the row(s) of the index corresponding to an individual species:
http://iucn-redlist-api.heroku.com/index/species/panthera-leo.json
You can use dashes for spaces, as a convenient replacement for the standard URL escape, %20.
The HTML format contains direct links to the species account pages. The CSV and JSON formats include a species_id column which can be used to construct species account URLs as follows:
http://iucn-redlist-api.heroku.com/details/species_id/0
To use the index JSON in Web pages directly, you may need JSONP padding; use the “.js” extension and add a “callback” parameter with the name of the function to use.
http://iucn-redlist-api.heroku.com/index/genus/Dioscorea.js?callback=show
I diagonally looked over the website and its sitemap and found no reference to a public API. All the output is HTML, and it makes sense that json parse method jsonp will not be able to make sense of it. First < it encounters, it will fail (as is apparent).
First of all, I would contact the site admin to simply ask if there is an API that will yield you XML or json or some other object notation that's convenient to work with.
Then there's the scenario where his or her answer would be 'no':
Parsing HTML is not something to be taken lightly and certainly not something you would write yourself unless absolutely necessary.
Luckily, there are ways to get data from html using jQuery.parseHTML(), pure ('vanilla') javascript ways you can use from within AngularJS and full-blown HTML parsing libraries such as HTML Agility Pack(for use in .NET), all of which can get you to the heart of the data within the DOM nodes you're trying to poke at.
There are many other libraries that might serve you better, but these examples will give you a good starting point to canvas the landscape of HTML parsing. This will take some looking into, but it will be more than worth it.

jQuery Ajax PUT an attachment to CouchDB doc

I have code that does POST attachments to Couch docs using jquery.form.js. That's all good, but I really need to allow the user to enter multiple files in the form, let's say 5 files for now, then in code iterate the five files in the form, creating one new Couch doc and attachment for each file. This is veeeery difficult if not impossible using only jQuery. It could be done using Couch "inline attachments" but then you would need a server-side (PHP probably) script to Base64 encode the binary image data. This really isn't an option for me because this is a Couchapp.
So the following code doesn't work, it generates an "invocation" error in jQuery. My assumption is that you can't simply add the reference to a binary file in the data attrib...
var url= _.couchUrl() + me.photoArgs.db +"/" +
couchDoc._id + "/attachment?rev=" + couchDoc._rev;
$.ajax({
type: "PUT",
url: url,
headers: {
"Content-Length": file.size,
"Content-Type": file.type
},
data: file,
success: function (response) {
console.log("Attachment was uploaded");
me.fileCnt--;
if (me.fileCnt == 0) console.log("Attachment(s) uploaded");
},
error: function (response) {
_.flashError('Attachment ajaxSubmit failed',me,response);
}
});
The code is clipped from inside a larger function. I've logged the url and the file, they both have correct data so they're not the issue.
Does anyone think the above should work? If so, what am I doing wrong?
Thanks a lot for your advice :-)
You have two options there:
Use inline attachments. You don't have to use PHP to decode base64 data: just add to your CouchApp /_utils/script/base64.js file (yes, it ships with CouchDB Futon) as CommonJS module and you'll be fine.
Use Multipart API (scroll a bit down for an example). I haven't much experience with jQuery to quick make a working prototype, but this question you may found helpful.
Update: found good working example how to upload multiple binary attachments to CouchDB using multipart API.

Using web2py, jQuery and ajax, how do you post to a database?

Using web2py I am trying to use ajax to put data into a table in my database, but I'm needing a bit of help.
Here is the function I am using (it currently has dummy data in the data section, rather than being passed data from a form):
function submitData(){
$.ajax({
type: "POST",
url: "requests",
data: {
id: 1,
user_id:111,
bottle_image:'',
bottle_name:'JJjman',
bottle_description:'Lol',
request_creationDate:'2000-01-01',
request_expiryDate:'2003-08-08',
request_fulfilled:false
},
success: function(){
alert('Posted data');
}
});
}
I have a html button with this function attached to its 'onclick', but at the moment all it does is reload the page and not pass any data onto the database. The success alert is also coming up.
Firebug is saying that the POST does contain all that data, but I'm not sure if the POST is actually going anywhere..
Am I missing any steps needed to actually pass this data to the database? Or could this just be that my data isn't all the right type for the database?
Cheers guys
Simply sending a post from the browser won't do anything on the server unless you have code on the server to handle the data and insert it into the database.
I strongly recommend you read through the relevant parts of the book to learn how to do this. The Overview chapter provides an introductory tutorial, including building an image blog that involves modeling a database table and creating a form to post records to that table.
Review the DAL chapter for details on modeling your database, the section on SQLFORM for details on creating forms associated with database tables, and the sections on ajax and components for details on using Ajax to post forms.
The easiest way to do what you want would be something like this:
In /models/db.py:
db = DAL('sqlite://storage.sqlite')
db.define_table('bottle',
Field('user_id')
Field('bottle_image'),
Field('bottle_name'),
Field('bottle_description', 'text'),
Field('request_creationDate', 'date'),
Field('request_expiryDate', 'date'),
Field('request_fulfilled', 'boolean'),
format='%(bottle_name)s')
In /controllers/default.py:
def index():
return dict()
def add_bottle():
return dict(form=SQLFORM(db.bottle).process())
In /views/default/add_bottle.load:
{{=form}}
In /views/default/index.html:
{{extend 'layout.html'}}
{{=LOAD('default', 'add_bottle.load', ajax=True)}}
Then go to /yourapp/default/index, and you will see a form, which will post records to the database via Ajax.

How can I pull Google Voice data?

Google Voice has XML URLs so I was wondering how somebody would pull the JSON part from the returned XML and parse it out to a page. Google Voice's search capability is busted right now and I want to get access to my history. I'm thinking that a synchronous call to all of the pages up to the last known page number in my history should do it...
This may be your best bet...
Read about dataType conversion here: http://api.jquery.com/extending-ajax/
Particularly the section that says:
You can define converters "inline," inside the options of an ajax call. For example, the following code requests an XML document, then extracts relevant text from it, and parses it as "mydatatype":
$.ajax( url, {
dataType: "xml text mydatatype",
converters: {
"xml text": function( xmlValue ) {
// Extract relevant text from the xml document
return textValue;
}
}
});
I don't know if this exact code snippet will return the JSON content properly, but at the very least it should strip it out of the XML response (you may need to add additional code to parse the returned "textValue" as JSON. Perhaps using the jQuery parseJSON method.
Maybe try:
$.ajax( url, {
dataType: "xml text mydatatype",
converters: {
"xml text": $.parseJSON;
}
}
});
Hope this helps.
XML and JSON are not the same data types. You will likely have to process the data as XML, if that's the only type your data is returned as. If the URL has .xml, you might try changing it to .json to see if it returns a JSON data type.
If you give us more information (examples, URLs, etc), someone might be able to help you better.

Resources