How can I pull Google Voice data? - ajax

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.

Related

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.

Receiving binary data using enyo.Ajax

I am trying to download a image, which is nothing but a chunk of binary data, using imagelink. For downloading i am using enyo.Ajax module. It is giving back an warning : "Ajax request set to handleAs JSON but data was not in JSON format " .
following is what i have implemented till now.
enyo.kind({
name:"enyo.sample.ajaxapp",
components:[
{kind:"onyx.Input",name:"urlinput", placeholder:"Input URL",classes:"input"},
{kind:"onyx.Button",name:"download",ontap:"fetch",classes:"button",content:"Fetch"},
{kind:"enyo.Control",name:"image",tag:"img",classes:"image"}
],
fetch:function(inSender,inEvent){
var ajax= new enyo.Ajax({
url:this.$.urlinput.getValue(),
handleAs:'blob'
});
ajax.go();
ajax.responseType='blob';
ajax.response(this,"processResponse");
ajax.error(this,"errorResponse");
},
processResponse:function(inSender,inResponse){
var img=this.$.image;
var blob=inResponse;
//var data=window.URL.createObjectURL(blob);
img.setSrc(blob);
},
errorResponse:function(inSender,inResponse){
console.log("error occured");
}
});
I wants to know whether is it not possible to get data apart from json/text/xml? If not, then how can i modify my code to get it downloaded. By default all the data received as JSON, so i am setting handleAs to bolb while creating ajax object. Do i need to change contentType or something else.
I don't think Ajax is the best way to request image data. You have (at least) two solutions:
Set the src attribute on an <img> tag and use onload to know
when the resource was downloaded.
Base 64 encode the image from the
server and set the src as the encoded data plus the appropriate
header info.
See this question for more details: Asynchronously load images with jQuery

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.

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

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.

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.
Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}
Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):
$.ajax({
type: 'GET',
url: 'http://username:api-key#www.kanbanpad.com/api/v1/projects.json',
contentType: 'application/json',
dataType: 'jsonp',
converters: {
'jsonp': jQuery.parseJSON,
},
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log(textStatus+': '+errorThrown);
}
});
If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.
It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")
So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.
It works just as well, it just requires an extra step is all.
Just for anyone that was looking for a solution.
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering
function to sanitize the response. You should return the sanitized data. The function
accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
I would change the content type in the dataFilter interceptor to json. Bear in mind this affects all ajax calls, so use info from data to decide which ones you want to convert.
Verify that your server is sending a jsonp response. This means the json should be enclosed with a string of your callback.
The callback name is passed in the parameters, and if you're not setting it explicitly, looks something like: jQuery15102810791094068532_1300988427891 (As per http://www.json-p.org/)
On your server, you need to format the response:
jQuery15102810791094068532_1300988427891({...json response ...});
Where you use the callback defined in your GET parameter 'callback'.
You might try setting the type to "json" and see if it works. I've had a number of parsererror's with the jquery's jsonp - you might try http://code.google.com/p/jquery-jsonp until it's a bit smoother.
Try changing your content-type to this
contentType: "application/json; charset=utf-8",

Resources