Reading a CSV file with jQuery - javascript

I have a downloaded CSV file which I would like to parse and use to create JSON objects for each record. The file is on my local machine but I have read that JavaScript has security measures in place that prevent access to these files.
Some examples show using csv.js with the following:
$.ajax({
url: "G:\downloaded_files\filename.csv",
aync: false,
success: function (csvd) {
csv_as_array = $.csv.toArrays(csvd);
},
dataType: "text",
complete: function () {
// use the array of arrays (variable csv_as_array)
// for further processing
}
});
When running this it just creates a GET request in the console. I am treading on unfamiliar territory here so any explanations would be great.
If I was to do this using Ruby I would do this, which hopefully will give you an indication of what I am trying to achieve:
require 'csv'
class FileRead
csv_text = File.read('/home/richardlewis/Downloads/csvtest.csv')
csv = CSV.parse(csv_text, headers: true)
csv.each do |row|
hash = row.to_hash
puts(hash)
end
end
I'm hoping this makes sense and someone can point me in the right direction.

You cannot call local files (from hard dics) using Ajax, or by any means from a web browser. You will have to publish your file using some sort of server. If you are using Linux you should have an Apache server already installed.
You need a REST service that will return your file in some format. JSON is the best, because it's easy to manipulate JSON data on the front-end.
It would look like this:
$.ajax({
url: "http://localhost:8080/services/rest/get_file", // your rest address
...
});

Related

Serializing DirectionsResult to JSON to send to my webservice not working fine

I am using the Google maps Javascript API and when the user changes the directions/route on the map (draggable is set to true) I want to send the new route/directionsResult to my webservice backend. The issue I am facing is when I serialize DirectionsResults using JSON.stringify I don't seem to be getting the full list of objects correctly converted to strings.
directionsDisplay.addListener('directions_changed', function () {
sendToBackendService(directionsDisplay.getDirections());
});
function sendToBackendService(result) {
var jsonToSend = JSON.stringify(result);
$.ajax({
type: 'POST',
url: './api/DirectionsUserModified',
data: jsonToSend,
error: processCallbackError,
success: function (apiJson) {
alert("post of new directions success");
}
});
}
The issue will always be related to the local environment of execution of your JavaScript code. So , the version of web browser you are using.
Maybe the object can't be serialized properly because the size limit is reached. The navigator uses the local storage as buffer during json serialization process. If the limit is reached, the String is simply truncated or an error is thrown.
You could have a look to this other post, maybe it'll help

Read specific character from file using JavaScript AJAX?

I need to find a way of reading data extracts from data files, where some of these files are quite large. The specific character place in the file is known and can be extracted using JavaScript code similar to that below (using JQuery).
The problem I am having is that my code reads the entire file into the buffer before processing, and for large files this is impractical. Is there a way that either code below can be altered or would perhaps a more efficient method be possible?
function startfn() {
var index = 1000;
$.ajax({
type: "GET",
url: "datafile.bin",
dataType: "text",
success: function(data) {procData(data,index);}
})
return 0;
}
function procData(strData, index) {
alert(strData.charCodeAt(index).toString(16)
+","+strData.charCodeAt(index+1).toString(16) +", "+
strData.charCodeAt(index+2).toString(16));
}
One way to do that is to use a backend service (Php for example) that do the extraction then just use ajax to get the result.

Use Javascript to receive variable from remote php file?

I need to retrieve a variable from a remote php file using javascript. I'm doing this using phonegap so same origin policy doesn't apply. I guess I need to use json / ajax but I can't find any tutorials that show me how to do this.
Is it as simple as having this in a php file:
<?php
$var = 'stuff';
echo json_encode( $var );
?>
And something like this in my application:
$.getJSON('mysite.com/test.php', function( data ) {
$.each( data, function( i, entry ) {
alert( entry );
});
Or is this totally the wrong approach? Any help would be great, thanks.
so for starters here are the docs on JQuery's ajax & the docs for JQuery's getJSON; and finally a slightly dated but decent tutorial explaining the basics on how to get started with raw .JSON files.
typically when I am dealing with JSON i am interacting with a web API; and most of the time they are RESTful api's at that... creating one is slightly more complex than what you have there but your thought process is on track.
here is a working access point to the google finance stock quotes api running a query on microsoft:
http://finance.google.com/finance/info?client=ig&q=MSFT
and an example of a json call (using jsonp for accessing an external url):
$.ajax({
url: 'http://finance.google.com/finance/info?client=ig&q=MSFT',
dataType: 'jsonp',
success: function(data){
console.log( data );
}
});
to make things easier i would try and break the work into two steps... first get a handle on accepting data from a api you know is functioning (ie google finance above)... and then move on to the next step of trying to write your own WebAPI in php (eg say you wanted to build your "variable" into a database or something a bit more useful than a flat php file). this way you can debug a bit easier with less hair loss
I'm using jquery and
I used to do like this in my PHP (if using json):
<?php
$var = 'stuff';
echo '{"var":"'.$var.'"}';
?>
it would return to a json.
and the ajax :
$.ajax({
url : "mysite.com/test.php",
dataType : "json",
data :"",
type : "POST",
success :
function (data){
alert(data.var);
}
});
(data and type in the ajax are not needed if you just want to get json from "mysite.com/test.php");

google spreadsheets - ajax call (get and post)

what I need to do is read the content of a "public" google spreadsheet (by public I mean that I saved the sheet clicking on "File > Publish to the web", so it's accessible without the need to be logged in into a google account), and, why not, write something into it too.
googlin' around, I found that I can access the sheet and get the xml equivalent of the sheet content with something like
https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values
It works great if I load that url into a browser. But I need to find a "javascript-way" to get and handle the returned value, ie the xml (or json, but xml would be preferable).
I tried to use an ajax call, but I think there's something messy with the protocol.. I can't get the server response correctly.
$.ajax({
type: "GET",
url: "https://spreadsheets.google.com/feeds/list/<sheetCode>/od6/public/values",
success: function(data){alert("yeah");},
error: function(){alert("fail..");},
dataType:"xml",
});
I also tried to get the json instead of xml, adding "?alt=json" to the url and changing the datatype, but I still have the problem..
Any idea / suggestion?
Thanks in advance, best regards
You need to request with a JSONP call and you need to specifiy a callback - method. This can be done in jQuery using:
var url = 'https://spreadsheets.google.com/feeds/list/<CODE>/od6/public/values?alt=json-in-script&callback=?';
jQuery.getJSON(url).success(function(data) {
console.log(data);
}).error(function(message) {
console.error('error' + message);
}).complete(function() {
console.log('completed!');
});
Documentation and samples for google spreedsheets .

Trying to open data retrieved from ajax to automatically download

Right now, I have a webapp that uses the jquery ajax to make a call (with params that change from call to call via a form) to my backend and retrieve an xml file. I want to put the xml data into a file with a different extension for a private application.
Basically I just want the user to be able to click a button, and it automatically prompts them to "open or save" a file containing the returned ajax xml data.
I've dabbled with sending a raw http header using php, but I can't figure out how to get it to work.
I'm writing all of this in javascript and jquery.
The only thing the below code does is (1)Make the Ajax Call, (2)Write the XML into an HTML page, (3) open the HTML page.
var format = function() {
$("button#format").click(function() {
$("#form").submit();
$.ajax({
url: "find",
beforeSend: function (xml) {
xml.overrideMimeType("application/octet-stream; charset=x-user-defined");
},
data: $("form#form").serialize(),
dataType: "html",
success: function(xml) {
xmlWindow = window.open("download.ivml");
xmlWindow.document.write(xml);
xmlWindow.focus();
},
error: function(request) {
$("#webdiv").html(request.responseText);
}
});
});
};
There is no need to force something like this into the AJAX paradigm, unless you need to play around with the data you retrieve before making it available for the user, then again, that should be able to be done in php. So I would do something like this:
<form id="format" action="download.ivml" target="_blank">
...
</form>
And in jquery modify the action like this
​$('#format')​.submit(function(){
// tweaking the post data, otherwise this whole block is not needed.
return true;
})​;
Finally on my server use a .htaccess file to handle that weird URL download.ivml
Options +FollowSymLinks
RewriteEngine on
RewriteRule ^(.*)download.ivml$ /path/to/where/I/process/the/request
not quite sure about the syntaxis of this last .htaccess file though.

Categories

Resources