ajax url for jstree on couchdb (via list function) - ajax

I have a CouchDB list function returning the html for the jstree. I am not sure if the url in my HTML form, to invoke the list is correct, since the jstree doesn't render. (with the same html pasted locally, it does). CouchDB is running on localhost.
The location of my list function is standard, "appname/app/lists/myList.js". I have tried several combinations of url, on the lines of "/appname/_design/appname/_list/listname/viewname".
What should be the correct form ?
Thanks.

The format should be as follows:
GET /db/_design/design-doc/_list/list-name/view-name
I copied this directly from the CouchOne Documentation.

OK, since I couldn't find a definite answer for rendering jstree with dynamic data using a CouchDB list, I went the other way and used after.js functionality in evently.
This is for anyone who might find it useful. This is what worked for me,
get the data using data.js
render it as <ul><li/></ul> in mustache.html
in after.js write the function for jstree as shown in the jstree documentation for html_data plugin
(after.js looks like this
function (e) {
$('.mytree').jstree({
"plugins" : [ "themes", "html_data", "checkbox" ]
});
}

Related

Getting an error trying to pull out text using Google Sheets and importxml()

I have a column of links in Google Sheets. I want to tell if a page is producing an error message using importxml
As an example, this works fine
=importxml("https://en.wikipedia.org/wiki/List_of_postal_codes_of_Canada:_T", "//td/b")
i.e. it looks for td, and pulls out b (which are postcodes in Canada)
But this code that looks for the error message does not work:
=importxml("https://www.awwwards.com/error1/", "//div/h1" )
I want it to pull out the "THE PAGE YOU WERE LOOKING FOR DOESN'T EXIST."
...on this page https://www.awwwards.com/error1/
I'm getting a Resource at URL not found error. What could I be doing wrong? Thanks
after quick trial and error with default formulae:
=IMPORTXML("https://www.awwwards.com/error1/", "//*")
=IMPORTHTML("https://www.awwwards.com/error1/", "table", 1)
=IMPORTHTML("https://www.awwwards.com/error1/", "list", 1)
=IMPORTDATA("https://www.awwwards.com/error1/")
it seems that the website is not possible to be scraped in Google Sheets by any means (regular formulae)
You want to retrieve the value of THE PAGE YOU WERE LOOKING FOR DOESN'T EXIST. from the URL of https://www.awwwards.com/error1/.
If my understanding is correct, how about this answer? Please think of this as just one of several possible answers.
Issue and workaround:
I think that the page of your URL is Error 404 (Not Found). So in this case, the status code of 404 is returned. I thought that by this, the built-in functions like IMPORTXML might not be able to retrieve the HTML data.
So as one workaround, how about using a custom function with UrlFetchApp? When UrlFetchApp is used, the HTML data can be retrieved even when the status code is 404.
Sample script for custom function:
Please copy and paste the following script to the script editor of the Spreadsheet. And please put =SAMPLE("https://www.awwwards.com/error1") to a cell on the Spreadsheet. By this, the script is run.
function SAMPLE(url) {
return UrlFetchApp
.fetch(url, {muteHttpExceptions: true})
.getContentText()
.match(/<h1>([\w\s\S]+)<\/h1>/)[1]
.toUpperCase();
}
Result:
Note:
This custom function is for the URL of https://www.awwwards.com/error1. When you use this for other URL, the expected results might not be able to be retrieved. Please be careful this.
References:
Custom Functions in Google Sheets
fetch(url, params)
muteHttpExceptions: If true the fetch doesn't throw an exception if the response code indicates failure, and instead returns the HTTPResponse. The default is false.
match()
toUpperCase()
If this was not the direction you want, I apologize.

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.

How to get a HTTPRequest JSON response without using any kind of template?

I am new to Django but i am advanced programmer in other frameworks.
What i intend to do:
Press a form button, triggering Javascript that fires a Ajax request which is processed by a Django View (creates a file) that return plain simple JSON data (the name of the file) - and that is appended as a link to a DOM-Element named 'downloads'.
What i achieved so far instead:
Press the button, triggering js that fires a ajax request which is process by a Django view (creates a file) that return the whole page appended as a duplicate to the DOM-Element named 'downloads' (instead of simple JSON data).
here is the extracted code from the corresponding Django view:
context = {
'filename': filename
}
data['filename'] = render_to_string(current_app+'/json_download_link.html', context)
return HttpResponse(json.dumps(data), content_type="application/json")
I tried several variants (like https://stackoverflow.com/a/2428119/850547), with and without RequestContext object; different rendering strats.. i am out of ideas now..
It seems to me that there is NO possibility to make ajax requests without using a template in the response.. :-/ (but i hope i am wrong)
But even then: Why is Django return the main template (with full DOM) that i have NOT passed to the context...
I just want JSON data - not more!
I hope my problem is understandable... if you need more informations let me know and i will add them.
EDIT:
for the upcoming questions - json_download_link.html looks like this:
Download
But i don't even want to use that!
corresponding jquery:
$.post(url, form_data)
.done(function(result){
$('#downloads').append(' Download CSV')
})
I don't understand your question. Of course you can make an Ajax request without using a template. If you don't want to use a template, don't use a template. If you just want to return JSON, then do that.
Without having any details of what's going wrong, I would imagine that your Ajax request is not hitting the view you think it is, but is going to the original full-page view. Try adding some logging in the view to see what's going on.
There is no need to return the full template. You can return parts of template and render/append them at the frontend.
A template can be as small as you want. For example this is a template:
name.html
<p>My name is {{name}}</p>
You can return only this template with json.dumps() and append it on the front end.
What is your json_download_link.html?
assuming example.csv is string
data ={}
data['filename'] = u'example.csv'
return HttpResponse(simplejson.dumps(data), content_type="application/json")
Is this what you are looking for?

How to load data using XHR in D3

I am experimenting with D3 on my localhost. I would like to load data to be visualized from an external source on the Internet.
I am looking for instruction/examples of how to how to load data using XHR in D3 (there is documentation here, but it does not suffice for me, I am looking for code snippets https://github.com/mbostock/d3/wiki/Requests)
I have tried the following and it does not work for me:
d3.xhr("http://example.org/json-test.json", function(data){
alert(data); //no data is returned
});
Thanks
In the latest version of D3, the first argument of the callback is the error, if any, and the second the data. No data in the first argument (which you're checking) suggests that the request was successful. See the documentation for more details.
update to the update:
The d3-request module has been superseded by the d3-fetch module. It handles JSON, CSV, TSV and plain text.
update:
Just in case someone arrives here looking for xhr in d3: this functionality is now supported in the d3-request module.
Your function callback should look like this
v---- missing param
d3.xhr("http://example.org/json-test.json", function(error, data){
// code...
});
That is the typical callback structure in javascript/node.js, error first then data.

jQuery AJAX Form, cannot send array?

I'm practicing my jQuery skills (ok, learning too) and experienced an issue. I got a file upload form with file input. I'm using this plugin (http://www.fyneworks.com/jquery/multiple-file-upload/#tab-Uploading) to upload multiple files at once. So I'm using following form input:
<input type="file" class="multi" name="photo[]" accept="gif|jpg|jpeg|png" maxlength="5"/>
Now... I'm trying to send an AJAX request to php file that will handle upload and server-side validation:
$('#upload_photos_s').click(function(q){
var photo = $('[name=photo[]]').val();
// Process form
$.ajax({
type: "POST",
url: "upload.php",
data: 'photo[]='+photo,
success: function(html){
alert($('[name=photo[]]').val());
$("#photo_upload_form").html(html);
}
});
return false;
});
While using Firebug I can see that there's only one file in photo[].
Any suggestions why? Is there something I missed?
Regards,
Tom
As it stands, you are indeed querying the value of the first photo[] member only. photo[].val() will not return an array containing all the values.
You would have to run through each member of photo[], e.g. using each(), to build an array of values.
However, I'm not sure this is the right path to go for whatever you want to do. You are aware that what you are doing is uploading the file names only, not their data?
It is not possible to upload files using AJAX without the help of additional tools like Flash-based SWFUPload. This is for security purposes to prevent scripts from having direct access to local files.
Maybe what you're trying to do is best suited for an approach where the form's target property points at an <iframe>. That would not trigger a reload of the page, but still submit the form the "traditional" way, allowing for old-school file uploads.
Well on the link you provided, there is a part called Ajax specifying the simplest way is to use the jQuery Form Plugin.
Documentation of plugins help a lot usually ^^.
Have a nice day :)

Resources