user4756836
user4756836

Reputation: 1337

GET file content from external JSON file

I am trying to get file content from external JSON file but I keep getting null on the alert.

JS:

function getText() {
    var result = null;
    var file = 'file.json';
    $.ajax({
        type: 'get',
        data: 'data',
        dataType: 'json',
        async: false,
        success: function() {
            var ranData = data[Math.floor(Math.random() * data.length)];
            result = ranData;
        }
    });
    alert(result);
}

External file:

var data = [
  ["a", "word 1"],
  ["e", "word 2"],
  ["i", "word 3"],
  ["o", "word 4"],
  ["u", "word 5"]
]

It works fine when I use data array in the same file instead. What am I doing? Any help will be appreciated!

UPDATE:

function readFiles() {
        var result = null;
        var file = 'dictionary.js';
        $.ajax({
            url: file,
            type: 'get',
            data: 'data',
            dataType: 'script',
            async: false,
            success: function(data) {
                var randomData = data[Math.floor(Math.random() * data.length)];
                result = randomData;
            }
        });
        alert(result);
 }

Still getting null value.

Upvotes: 0

Views: 185

Answers (2)

eosterberg
eosterberg

Reputation: 1452

The file you are trying to load is not in the JSON format, its javascript code. Remove the var = statement and everything should be fine.

Upvotes: 0

Indy
Indy

Reputation: 4957

You forgot to pass data argument to success callback function, but also you forgot to set url parameter to which the request is sent:

 function getText() {
    var result = null;
    $.ajax({
        urL: 'file.json',
        type: 'GET',
        data: 'data',
        dataType: 'json',
        async: false,
        success: function(data) {
            var ranData = data[Math.floor(Math.random() * data.length)];
            result = ranData;
        }
    });
    alert(result);
}

And one more thing. You really shouldn't be using async:false in your ajax because synchronous ajax will completely freeze the browser until ajax request is finished. You should process your data inside success callback. Also I noticed that in your success callback you're checking for array length data.length, well this probably won't work since you're expecting to get back data from server in JSON format (you set dataType options to json)

Upvotes: 1

Related Questions