Reputation: 581
Im getting a syntax error in FireFox when using $.parseJSON()
. The same code works properly on Chrome/Chromium, and Safari.
I call this function to get a random generated token to set.
function getToken() {
var url = "/csrf_token_generate";
$.ajax({
url: url,
method: "GET"
}).done(function(data) {
console.log(data); // Logs the data from the call
var json = $.parseJSON(data); // Where the error occurs
token = json.token;
console.log(token);
});
}
The URL /csrf_token_genrate
returns a JSON object similar to {"token":"$2y$10$jcr.P3FNqeji6RqD93LnxeIKs9gYNiPj7cboahz8RCCSgKw7VOfhi"}
In the URL, I am setting the Content-Type
to application/json
which works in every other browser.
The error Im getting is this
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
n.parseJSON() jquery.min.js:4
getToken/<() wheel.bak.js:94
n.Callbacks/j() jquery.min.js:2
n.Callbacks/k.fireWith() jquery.min.js:2
x() jquery.min.js:4
.send/b/<() jquery.min.js:4
The object that is being console.log()
'ed is this Object { token: "$2y$10$60vxSZiVqushBLVHSR5jPO6MquD4…" }
I just can't seem to track down why it won't work in only FireFox, but works fine in other browsers.
UPDATE 1
I figured out that firefox was trying to parse an already parsed object, so I changed the code to be along this
function getToken() {
var url = "/csrf_token_generate";
$.ajax({
url: url,
method: "GET"
}).done(function(data) {
var json = data;
token = json.token;
console.log(token);
});
}
Which now works in firefox, but not Chromium.
So what is there to do than?
Upvotes: 0
Views: 3690
Reputation: 82
I think you should check the Response Headers
-> Content-Type
to find the actual Data Type
.
And the compatible code should like this.
# for chrome
if(typeof data === 'string') {
}
#for firefox
if(typeof data === 'object') {
}
Upvotes: 1