I am trying to create a jsfiddle for one of the dc.js examples. I am not able to load an external file using a URL and d3.csv().
Can someone please suggest how to load a csv file using d3.csv in jsfiddle.
The approach I usually use for CSV data in JSFiddle examples is
a. Put the data in a <pre> block at the end of the HTML mark-up, usually with the id "data".
b. Add pre {display:none;} to the CSS.
c. Replace the d3.csv(filename, callback) function call with a d3.csv.parse(text) call, using the text content of the <pre> block as the input to the parse function.
Because the parse function doesn't use a callback, it just returns the data array, you need to save that output in a variable of the same name as your callback data parameter.
In other words, if your example looks like
d3.csv("data.csv", function(error, data) {
if(error){console.log("Could not read " + "data.csv");
/* Do something with `data` here */
});
The JSFiddle-friendly version would look like:
//d3.csv("data.csv", function(error, data) {
// if(error){console.log("Could not read " + "data.csv");
var data = d3.csv.parse( d3.select("pre#data").text() );
/* Do something with `data` here */
//});
If you would rather have a full working example that uses the file-reading methods as intended, there are other options as mentioned in the comments. Tributary also allows external data files I think.
Related
I found this page How can I pretty-print JSON using node.js? and I think it's useful, but I have one question: I have a page that give a result from a request sparql in an array, and I want to take just one line of this results with a button "add" that is insert in the last column of the line, and when I take the line in Json I want to write it in a file json that already exist with other data. The button call the next function:
function add(param) {
res= param;
$.ajax({
type: "POST",
url: "....",
data: { nom:resource,abstract:resume,photo:src,indice: res ,fichier:$("#myselect" ).val()}
})
.done(function( msg ) {
alert( "ajout réussie"+msg);
window.location.reload();
});
};
Where res is the index for the line that I want to add, and data all data I need to add.
So I want to know how I can change this code to use the last code posted by "Larry Battle". I have to put his code in a file "add.js" and I call this file in url? Or How?
Link for my example: https://www.dropbox.com/s/noyh1ltwljlpevw/Capture%20du%202014-05-01%2019%3A05%3A04.png
The easiest way might be to require the original json file, add the new data in memory, then save the object back as a pretty json file (overwriting the original if you like).
I'm not sure what you meant by "res is the index of the line I want to add", so I'll assume it's going to be the property name in the javascript object that you serialize to JSON. So in general it'd look something like this:
var fileData = require('/path/to/jsonData.json');
// fileData is now a JS object that was parsed from the json file); this is a sync operation.
fileData[res] = data; // data object from your existing code.
// write fileData to a JSON file like you were going to do before.
Just as the title says, I want to know how to access the data from the temporary file stored by Django, when a file is uploaded, inside a view.
I want to read the data uploaded values so I can make a progress bar. My methodology is to perform a jquery getJSON request:
function update_progress_info() {
$progress.show();
$.getJSON(progress_url, function(data, status){
if (data) {
var progress = parseInt(data.uploaded) / parseInt(data.length);
var width = $progress.find('.progress-container').width()
var progress_width = width * progress;
$progress.find('.progress-bar').width(progress_width);
$progress.find('.progress-info').text('uploading ' + parseInt(progress*100) + '%');
}
window.setTimeout(update_progress_info, freq);
});
};
where progress_url is the view I have that handles the uploaded file data:
# views.py (I don't know what to do here):
def upload_progress(request):
for line in UploadedFile.temporary_file_path
response = (line)
return response
Django handles uploaded files with UploadHandler defined in settings.py with this name FILE_UPLOAD_HANDLERS that defaults to this tuple:
FILE_UPLOAD_HANDLERS =
("django.core.files.uploadhandler.MemoryFileUploadHandler",
"django.core.files.uploadhandler.TemporaryFileUploadHandler",)
The behavior with file uploads is that if the file is less than 2.5 mg then it will be kept on memory, hence, they will not be written in disk as temporary files.
If the file weights more, it will be written in chunks in the FILE_UPLOAD_TEMP_DIR in the settings.py. That's the file you'll have to query to know how many bytes have been uploaded.
You can access the uploaded/uploading files through your request variables in views like this: file = requests.FILES['file'] . There, file variable will have the type UploadedFile which contains a method temporary_file_path with the address of the file in the disk being uploaded. (Note: only files larger than 2.5 mg will have this methods) so there you may get the size of the file being uploaded.
Another way to do this is create your own UploadHandler like a ProgressBarUploadHandler and add it to your file upload handlers. This is the way the docs recommend it. Here are some snippets and tutorials for doing it.
If you need any more info the doc is really well documented.
I hope you find this helpful. Good luck.
I've used "Google AJAX Transliteration API" and it's going well with me.
http://code.google.com/apis/ajaxlanguage/documentation/referenceTransliteration.html
Currently I've a project that I need all input fields in every page (input & textarea tags) to be transliteratable, while these input fields differs from page to page (dynamic).
As I know, I've to call makeTransliteratable(elementIds, opt_options) method in the API call to define which input fields to make transliteratable, and in my case here I can't predefine those fields manually. Is there a way to achieve this?
Thanks in advance
Rephrasing what you are asking for: you would like to collect together all the inputs on the page which match a certain criteria, and then pass them into an api.
A quick look at the API reference says that makeTransliteratable will accept an array of id strings or an array of elements. Since we don't know the ids of the elements before hand, we shall pass an array of elements.
So, how to get the array of elements?
I'll show you two ways: a hard way and an easy way.
First, to get all of the text areas, we can do that using the document.getElementsByTagName API:
var textareas = document.getElementsByTagName("textarea");
Getting the list of inputs is slightly harder, since we don't want to include checkboxes, radio buttons etc. We can distinguish them by their type attribute, so lets write a quick function to make that distinction:
function selectElementsWithTypeAttribute(elements, type)
{
var results = [];
for (var i = 0; i < elements.length; i++)
{
if (elements[i].getAttribute("type") == type)
{
results.push(elements[i]);
}
}
return results;
}
Now we can use this function to get the inputs, like this:
var inputs = document.getElementsByTagName("input")
var textInputs = selectElementsWithTypeAttribute(textInputs, "text");
Now that we have references to all of the text boxes, we can concatenate them into one array, and pass that to the api:
var allTextBoxes = [].concat(textareas).concat(textInputs);
makeTransliteratable(allTextBoxes, /* options here */);
So, this should all work, but we can make it easier with judicious use of library methods. If you were to download jQuery (google it), then you could write this more compact code instead:
var allTextBoxes = $("input[type='text'], textarea").toArray();
makeTransliteratable(allTextBoxes, /* options here */);
This uses a CSS selector to find all of the inputs with a type attribute of "text", and all textareas. There is a handy toArray method which puts all of the inputs into an array, ready to pass to makeTransliteratable.
I hope this helped,
Douglas
I want to make an AJAX call to an HTML-returning page, extract part of the HTML (using jQuery selectors), and then use that part in my jQuery-based JavaScript.
The AJAX retrieval is pretty simple. This gives me the entire HTML document in the "data" parameter of the callback function.
What I don't understand is how to handle that data in a useful way. I'd like to wrap it in a new jQuery object and then use a selector (via find() I believe) to get just the part I want. Once I have that I'll be passing it off to another JavaScript object for insertion into my document. (This delegation is why I'm not using jQuery.load() in the first place).
The get() examples I see all seem to be variations on this:
$('.result').html(data);
...which, if I understand it correctly, inserts the entire returned document into the selected element. Not only is that suspicious (doesn't this insert the <head> etc?) but it's too coarse for what I want.
Suggestions on alternate ways to do this are most welcome.
You can use your standard selector syntax, and pass in the data as the context for the selector. The second parameter, data in this case, is our context.
$.post("getstuff.php", function(data){
var mainDiv = $("#mainDiv", data); // finds <div id='mainDiv'>...</div>
}, "html");
This is equivalent to doing:
$(data).find("#mainDiv");
Depending on how you're planning on using this, $.load() may be a better route to take, as it allows both a URL and a selector to filter the resulting data, which is passed directly into the element the method was called on:
$("#mylocaldiv").load("getstuff.php #mainDiv");
This would load the contents of <div id='mainDiv'>...</div> in getstuff.php into our local page element <div id='mylocaldiv'>...</div>.
You could create a div and then put the HTML in that, like this…
var div = $("<div>").html(data);
...and then filter the data like this…
var content = $("#content", div.get(0));
…and then use that.
This may look dangerous as you're creating an element and putting arbitrary HTML into it, but it's not: anything dangerous (like a script tag) will only be executed when it's inserted into the document. Here, we insert the data into an element, but that element is never put into the document; only if we insert content into the document would anything be inserted, and even then, only anything in content would be inserted.
You can use load on a new element, and pass that to a function:
function handle(element){
$(element).appendTo('body');
}
$(function(){
var div = $('<div/>');
div.load('/help a', function(){handle(div);});
});
Example: http://jsbin.com/ubeyu/2
You may want to look at the dataFilter() parameter of the $.ajax method. It lets you do operations on the results before they are passed out.
jQuery.ajax
You can do the thing this way
$.get(
url,
{
data : data
},
function (response) {
var page_content = $('.page-content',response).get(0);
console.log(page_content);
}
)
Here in the console.log you will see the inner HTML of the expected/desired portion from the response. Then you can use it as your wish
I'm really new to using JSON to handle my Ajax Request and Response cycle. I've previously used just plain old parameters passed as POST data and I've rendered straight HTML in the response which was then placed into the DOM. As I've looked at various examples and read through various tutorials, it seems like a fairly common practice to simply build a string from the JSON object mixed with HTML that's been hard coded into the string and then assign the string as innerHTML to some element.
A common example looks something like this:
var jo = eval(req.responseText);
var strTxt = '<span>' + jo.f_name + ' ' + jo.l_name + '</span><br/>' + 'Your Age Is: ' + jo.age + '<br/>';
$('myDiv').innerHTML = strTxt;
Is there a more elegant (or correct) way of handling the JSON response so that I'm not hard coding HTML in the javascript? Or is this pretty much how people do it?
P.S. Links to tutorials or other sources are appreciated.
I steer away from writing a lot of HTML within JavaScript strings. I prefer separation of structure from data manipulation. The better alternative is to place that code in the page, load the values based off the ID's, and show/hide it if necessary:
<div id="codeBlock" style="visible=false;">
<span id="val1"></span>
<br/>
<span id="val2"></span>
<br/>
</div>
............
<script>
var jo = eval(req.responseText);
$('val1').innerHTML = jo.f_name + ' ' + jo.l_name;
$('val2').innerHTML = 'Your Age Is: ' + jo.age;
$('codeBlock').show();
</script>
That might not be exactly what you want to do but you get the idea.
You could create the elements in the DOM using javascript instead of just dropping them into the innerHtml of the DIV, something like the following (untested):
var mySpan = document.createElement("span");
var spanContent = document.createTextNode(jo.f_name + ' ' + jo.l_name);
mySpan.appendChild(spanContent);
var myBr = document.createElement("br");
mySpan.appendChild(myBr);
var otherSpanContent = document.createTextNode('Your Age Is: ' + jo.age);
mySpan.appendChild(otherSpanContent);
mySpan.appendChild(myBr);
$('myDiv').appendChild(mySpan);
You could check out a templating engine such as PURE - may be a bit hard to get into at first but it supports many major javascript frameworks (and DOMAssistant which is nice) and separates html from the data.
The objects created from JSON are standard Javascript objects, therefore you can easily use jQuery selectors to create or access DOM elements and insert content from your JSON objects.
eg.
// Create a new span element and set its text
var personSpan=$("<span>").text(jo.f_name + ' ' + jo.l_name);
// Append the span to the existing myDiv element
$("myDiv").append(personSpan);
// Create a new div element (better then br) and set its text
var personDiv=$("<div>").text("Your Age Is: " + jo.age);
// Append the new div to the existing myDiv element
$("myDiv").append(personDiv);