Fix: The issue was, as Phil pointed out, using AJAX to try and load a JSON that was already in the same folder as the code. All I had to do was remove the $.getJSON()
command and use var truthpg = require('./truthpg.json')
. Thanks to all who helped me fix this!
Updated code to display errors:
function truthCommand(arguments, recievedMessage) {
var truthpg = new Array();
function loadQuestions() {
$.getJSON("truthpg.json", function(data) {
truthpg = data;
})
.fail(function(data, jqXHR, textStatus, errorThrown) {
console.error(textStatus, errorThrown)
console.log("load failed");
recievedMessage.channel.send('load failed');
});
}
loadQuestions()
}
Result
Original question/code: I've been trying to code a Discord bot using node.js and discord.js. The code causing issues is:
function truthCommand(arguments, recievedMessage) {
var truthpg = new Array();
function loadQuestions() {
$.getJSON("truthpg.json", function(json) {
truthpg = json;
})
.fail(function() {
console.log("load failed");
recievedMessage.channel.send('load failed');
});
}
loadQuestions()
}
And the test JSON I'm trying to retrieve is:
[
"tpg1",
"tpg2",
"tpg3",
"tpg4",
"tpg5"
]
Everything I've tried hasn't stopped the "fail" code from executing. What should I fix/do next to load the JSON properly and be able to add code that uses the array? This is only my second JavaScript project, so I'm not very familiar with the language and how to use it.