0

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.

0

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

the url wasn't set and the file contains invalid data.
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.