Here is my relevant jQuery code:
$.get('sampleData.csv', function(data) {
var lines = data.split('\r\n');
The first few line of the sampleData.csv file look like this:
2009,0,2,29.0000
2009,0,6,655.6200
I get 2 errors.
On the first line of csv file I get the error
syntax error
On the 2nd line of code I get the error
data.split is not a function
What am I doing wrong?
ETA According to the firebug console, the responseText is the following:
2009,0,2,29.0000\r\n2009,...\r\n2011,10,30,494.3500\r\n
ETA I added an alert of the data before I try splitting it into lines, and I get the following:
[Object XMLDocument]
I believe you misunderstand what jQuery.get() is suppose to be used for.
From it's doc page, "...Load data from the server using a HTTP GET request...."
Doing a $.get() on a file will not get you that file's data into a structure that can be used. You have to request this through a server which will then provide the .csv data ... it should look something like the following
$.get('http://url.to.server.page',function(data){
var dataStr = new String(data);
var lines = dataStr.split('\n');
});
EDIT::
Since you say the data is being 'loaded' properly, try this fiddle. It works just fine.
EDIT2::
Your last edit gave some interesting insight. When it pulls the .csv file, its converting it to a type of XML vs text. Try the following:
$.get('http://url.to.server.page',function(data){
var dataStr = new String(data);
var lines = dataStr.split('\n');
},dataType='text');
This should put the returning 'data' into the proper string format.
jQuery code:
$.get('data.csv', function(data) {
var lines = data.split('\r\n');
});
works until jquery version 1.5.
From version 1.5 callback function in get() method is passed "jqXHR" object, not "XMLHttpRequest" object.
Code can be changed to:
$.get('data.csv', function(data) {
var lines = data.split('\r\n');
}, "text");
Then it will work.
http://api.jquery.com/jQuery.get/
Your almost there. Missing the final parenthesis and need a different split character.
$.get('sampleData.csv', function(data) {
var lines = data.split(',');
});
Edit
Ah you changed your CSV to two lines i assumed it was just one line seperated by commas not data seperated by new line also seperated by commas. The below I retested and worked fine for me.
<html>
<head>
<script type="text/javascript">Jquery Reference or insert directly here </script>
</head>
<body>
<script>
$(document).ready(function(){
$.get('csv.csv', function(data) {
// Split the lines
var lines = data.split('\n');
var i = 0;
for(i=0; i<lines.length; i++)
{
alert(lines[i]);
}
});
});
</script>
</body>
</html>
I just had that html file on my desktop with the csv you pasted in the same place.