Title: JavaScript variable not correctly interpreted
Tags: javascript;ajax
Question: In the header section of a HTML page, I have the following JavaScript-/Ajax-Function:
function getDataFromBackend(cmp){
$.ajax({
method: 'GET',
url: 'getRun.php?run='+cmp,
dataType: 'script',
success: loadData
getRun returns an array like [[2, 4, 5, 57]]
loadData is defined as follows:
function loadData(dataFromAjax){
setTimeout(function () {
console.log(dataFromAjax);
chartRunnerDist.load({
columns: dataFromAjax
});
}, 100);
}
In the console, I see the correct values. If I copy the console content behind columns: part manually, everything is fine. But dataFromAjax doesn't seem to be interpreted correctly. Do I have to explicitly convert it to an array?
Comment: typeof returns string, still JSON.parse does not help.

Comment: My php returns:
[[1, 0, 6, 7, 9, 18, 29, 29, 25, 78, 65, 99, 109, 141, 154, 189, 192, 259, 208, 218, 239, 229, 250, 237, 199, 160, 127, 143, 106, 95, 90, 79, 52, 62, 49, 46, 39, 37, 17, 21, 22, 14, 15, 8, 9, 8, 4, 4, 4, 2, 3, 1, 2, 2, 0, 1, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, ]]

Comment: can you add a snapshot of your console.log ?

Comment: That depends, generally ajax only returns strings, not arrays, but jQuery does does do some magic based on things like `dataType` to convert certain structures. Why is your `dataType` set to `script`, what exactly is the PHP returning?

Comment: Why not just try `console.log(typeof dataFromAjax);` and see what you've got

Comment: What is `chartRunnerDist()`? What do you mean exactly by "interpreted correctly"?

Here is the accepted answer: You may have to parse the response to convert it from a string to an object. Use JSON.parse(dataFromAjax)
Comment for this answer: That solved my issue. (At first, I still received an error message, but that was for another reason.) Thank you all.

Here is another answer: try this
function loadData(dataFromAjax){
setTimeout(function () {
console.log(dataFromAjax);
chartRunnerDist.load({
columns: dataFromAjax[0]
});
}, 100);

{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 2, 'CommentCount': 6, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2017:00:08/29/17', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<javascript><ajax>', 'Title': 'JavaScript variable not correctly interpreted', 'ViewCount': 60, 'id': 45947243, 'user_AboutMe': None, 'user_AccountId': 9659709.0, 'user_DisplayName': 'heckerf', 'user_Reputation': 33.0, 'user_Views': 2.0, 'user_id': 7168202.0}}