ReferenceError: CSV is not defined - javascript

I am using the jquery.csv-0.71.min.js lib to load a csv file and convert it to an array. However, when loading my webpage:
<script src="assets/lib/jquery/dist/jquery.min.js"></script>
<script src="assets/lib/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Jquery-csv -->
<script src="assets/js/jquery.csv-0.71.min.js"></script>
<script>
(function() {
var data;
var url = 'data/data.csv';
function makeRequest(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {/*run code*/}
};
xhr.send(null);
}
})();
data = CSV.toArrays(xhr.responseText);
console.log(data);
</script>
I get in the console:
ReferenceError: CSV is not defined at 'data = CSV.toArrays(xhr.responseText);'
Any recommendations what I am doing wrong?
I appreciate your replies!
UPDATE
I put my code into the document read funciton, however, I still get the same error as above.
$(document).ready(function() {
(function() {
var data;
var url = 'data/data.csv';
function makeRequest(url) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onload = function() {
if (xhr.readyState === 4 && xhr.status === 200) {/*run code*/
}
};
xhr.send(null);
}
})();
data = CSV.toArrays(xhr.responseText);
console.log(data);
});

You code is executed before browser loads the CSV script.
Wrap you JavaScript code with
$( document ).ready(function() {
// PUT YOUR JavaScript CODE HERE
});
This will make browser to wait, until all your scripts are loaded, and only after to execute the code.
You can check the documentation of the jquery csv here. It says that you should invoke methods like this:
$.csv.toArrays(csv);

Related

how to use embed code in javascript variable

I have this variable in js :
var video_embed = '<script src="https://stream.laminor.academy/1qwyvs9ystd9/embed"><\/script>';
$('.my_video').after("<div class='col-xs-12' id='video_content'>"
+ video_embed +
"</div>");
but my rendered HTML code is :
<div class="col-xs-12" id="video_content">
<script src="https://stream.laminor.academy/1qwyvs9ystd9/embed"></script>
</div>
embed code not working!
Thanks for help
when you generate script tags after the document is loaded, it won't run.
You need to download the script and execute it :
//Code that will download the script
function loadScript() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
// Making sure there's no error
if (this.readyState == 4 && this.status == 200) {
// Executing the script
eval(this.responseText)
} else if (this.readyState == 4) {
// If the server responded with something else than a 200 OK
console.warn(this.status)
}
};
xhttp.open("GET", "https://stream.laminor.academy/1qwyvs9ystd9/embed", true);
xhttp.send();
}
// Executing the function
loadScript()
Let me know if it isn't working.

Accessing JSON from last.fm API

I'm very new to JavaScript and have been looking for a solution for a while with no success. I'm trying to use the Last.fm API to retrieve the currently playing track on my account. This is what I have so far:
<html>
<body>
<p>this is an experiment!</p>
<script type="text/javascript">
const request = new XMLHttpRequest();
request.open('GET', 'http://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user='+[MY_USERNAME]+'&api_key='+[MY_API_KEY]+'&format=json');
request.send();
request.onload = () => {
if (request.status === 200) {
console.log("Success");
var song = JSON.parse(request.response).recenttracks.track[0].name;
console.log(song);
}
};
request.onerror = () => {
console.log("error")
};
</script>
</body>
</html>
and I get an error in the console when I open the file in my browser. Any help is appreciated :)
Update: everything worked when I gave it the direct URL, e.g. I took out the +s and put the API key directly in.
I checked your code with the test-account and it works fine. So probably you get the empty result, let's add some checks:
request.onload = () => {
if (request.status === 200) {
// look at the response
console.log(request.response);
const recenttracks = JSON.parse(request.response).recenttracks;
if (!recenttracks.track || !recenttracks.track.length) {
console.log('track is empty');
return;
}
const song = recenttracks.track[0].name;
console.log(song);
}
};
It looks like you should use onreadystatechange to catch the response instead of onload.
Example:
request.onreadystatechange = function() {
if (this.status == 200) {
console.log(this.responseText);
}
};
You can read more about XMLHttp Requests here:
https://www.w3schools.com/xml/ajax_xmlhttprequest_send.asp

How to access data from the external JSON file to use in the javascript file, no JQuery, in notepad

I have an external json file and I would like to access the data from it in my javascript file or my html file. I've tried looking at other solutions but its not working, I don't have jQuery so please don't include it.
What I would like for this to do is load the json file and then display the contents on the web page.
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'PATIENT5.json', true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
function callback(data)
{console.log(data);
}
PATIENT5.json
["Harry","35"]
I tried adding the console.log(data); but when I checked the console there wasn't anything there. Anything would be helpful this is my first time using javascript/html! Thanks!!
Add the code with script tag. and call the function.
<script type="text/javascript">
function loadJSON(file, callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', file, true);
xobj.onreadystatechange = function () {
if (xobj.readyState == 4 && xobj.status == "200") {
callback(xobj.responseText);
}
};
xobj.send(null);
}
//usage:
loadJSON("file.json", function(text){
var data = JSON.parse(text);
console.log(data);
});
</script>

jQuery not working with XMLHttpRequest object

I have an index.php page which loads info.php through AJAX. The info.php content is loaded like this:
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "info.php", true);
xhttp.send();
}
(function() {
loadDoc()
})();
setInterval ( "loadDoc()", 5000 );
</script>
The info.php file has the following code to do a count up/down from/to a specific number.
<div class="timer count-title count-number" data-from="2000" data-to="300" data-speed="1500"></div>
<script src='includes/jquery-3.2.1.min.js'></script>
<script src="includes/counter.js"></script>
When I visit info.php directly the counter works perfectly fine. However, if I visit index.php, the counter is not even showing. I had the same issue with other jQuery scripts. Even if index.php includes jQuery and the other scripts it still doesn't work. I do want the number to go through the AJAX call since it keeps updating.
Is there a simple solution?
you can do it by JQuery like as follow...
function loadDoc(){
console.log( "call done" );
$( "#data" ).load( "info.php", function() {
console.log( "Load done." );
});
};
$(function(){loadDoc();});
setInterval (loadDoc, 5000 );
I think their problem with your function statement checks this for the following script...
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("data").innerHTML = this.responseText;
}
};
xhttp.open("GET", "info.php", true);
xhttp.send();
}
$(function(){loadDoc();});
setInterval (loadDoc, 5000 );

Pinterest pins through HTML/JavaScript

I Have been using pins to get the information of a pin from pinterest.
The following is the script being used:
<script type="text/javascript">
function getresponse1()
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids="+{Pin ID});
alert(xmlHttp.status);
var data=xmlHttp.responseText;
var jsonResponse = JSON.parse(data);
var pin_url="www.pinterest.com/pin/"+pin_id+"/";
var page_name=(jsonResponse["data"][0].pinner.full_name);
alert(page_name);
}
</script>
Whenever XMLHttpRequest() method is being invoked the status returned is always 0 and the xmlHttp.responseText is empty.
But when the link is opened in a browser the response is correct and has all the information of the pin.
EDIT:
Tried implementing cross domain too. But yet the status returns 0.
New Script:
<script type="text/javascript">
function getresponse1()
{
var xhr = new XMLHttpRequest();
var url="https://widgets.pinterest.com/v3/pidgets/pins/info/?pin_ids=308074430730714588";
if ("withCredentials" in xhr) {
xhr.open("GET", url, true);
} else if (typeof XDomainRequest != "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
alert(xhr.status);
var data=xhr.responseText;
}
</script>
Please let me know where i'm making mistake. Thanks in advance
Note: I'm using Chrome browser
This is an general issue, as you try to do an ajax request to a different site (cross domain).
This isn't an new issue at all, I think here it is well explained and this posts provide also some thoughts about possible solutions.
AJAX is asynchronous, so your data will only be available from some kind of callback.
xhr.onload = function() {
if (xhr.status >= 200 && xhr.status < 400) {
var data = JSON.parse(request.responseText);
}
};

Categories