JSON syntax error in firefox only - javascript

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?

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') {
}

Related

Parsing ajax JSON response in a loop

So I try to parse json response from ajax request with JSON.response, but it doesn't work
the example of the json response from my api looks like this :
{"cn":"3335621215844","status":5,"proxy":"207.154.231.213:8080","error":"Received HTTP code 400 from proxy after CONNECT"}
here's the error from the broswer debug :
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
here is my code :
function cn_doCheck() {
var proxy_counter = 0;
var cn_list = $("#cn_input").val().split('\n');
var proxy_list = $("#proxy_input").val().split('\n');
var i=0;
if (cn_list!="" && proxy_list!="") {
$.each(cn_list, function(index, value){
if (i>proxy_list.length) {
i=0;
}
$.ajax({
type : 'post',
data : {
cn: value,
proxy: proxy_list[i]
},
url : 'api_test.php',
async : true,
beforeSend: function(response){
$("#loader").empty();
$("#loader").append("Checking "+cn_list.length+" in total");
},
success: function(response){
},
complete: function(response){
var result = JSON.parse(response);
$("#cn_live").append(result.cn+"|"+value+"|"+proxy_list[i]+"\n");
i++;
}
});
});
}else{
alert("Card/Proxy list can't be empty!");
}
}
Seems like response is already a JavaScript object not a string, you do not need to parse that again.
Update: Ajax success() only gets called if your web server responds with a 200 OK HTTP header - basically when everything is fine. Where as, complete() will always get called no matter if the ajax call was successful or not - maybe it outputted errors and returned an error - complete() will still get called.
Please execute your code inside success call back to avoid unwanted scenario.
Problem
It appears that the response is already in JSON format.
Parsing the response:
complete: function(response){
var result = JSON.parse(response);
$("#cn_live").append(result.cn+"|"+value+"|"+proxy_list[i]+"\n");
i++;
}
Response:
{
"cn": "3335621215844",
"status": 5,
"proxy": "207.154.231.213:8080",
"error": "Received HTTP code 400 from proxy after CONNECT"
}
If you try to use JSON.parse with an object that is already in JSON format, it will give you the error:
Uncaught SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
Solution
So I think you do this instead:
var result = response

Javascript jquery - Uncaught TypeError: Illegal invocation

I am trying to test a login web service by posting some xml to log in and it's returing this error:
Uncaught TypeError: Illegal invocation
Here is the code:
$(document).ready(function() {
var data = $.parseXML("<authenticationDetail><userName>username</userName><password>passw</password></authenticationDetail>");
var url = "http://127.0.0.1:8000/thelogin.ws";
$.ajax({
data: data,
type: "POST",
contentType: "application/xml",
url: url,
dataType: "xml",
success: function(xml) { // callback called when data is received
alert("success to post");
},
error: function() { // callback called when error
alert("fail to post");
}
});
});
How can I fix this?
Try changing :
var data = $.parseXML("<authenticationDetail><userName>username</userName><password>passw</password></authenticationDetail>");
To :
var data = "<authenticationDetail><userName>username</userName><password>passw</password></authenticationDetail>";
You're sending XML, not parsed XML.
You're setting dataType to xml, but you're doing $.parseXML and sending the parsed XML (an object).
var data = $.parseXML("<authenticationDetail><userName>username</userName><password>passw</password></authenticationDetail>");
data is an object, not a valid XML string.
JQuery needs the unparsed XML string for this request to work.
So just omit the $.parseXML part and it should work.

Uncaught SyntaxError: Unexpected end of input in parseJSON method javascript

In a webpage that uses javascript, I pass data to a hidden input field using
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
and then later access that data using
waypts_input = $.parseJSON($("#waypt_sel").val())
This works, except that sometimes it gives a
Uncaught SyntaxError: Unexpected end of input
. I tracked the error to this line with the json parsing. but I am baffled because this works sometimes but sometimes it doesn't for the same, identical string.
I checked the values that are passed to the html inputs and it works and doesn't work for the same values.
Here's an example of the json string I am passing:
"[{\"location\":\"8.3353156, 80.3329846\",\"stopover\":true}, {\"location\":\"8.0326424, 80.7446666\",\"stopover\":true}, {\"location\":\"7.9577778, 80.667518\",\"stopover\":true}, {\"location\":\"7.953208, 81.006675\",\"stopover\":true}, {\"location\":\"7.885949, 80.651479\",\"stopover\":true},{\"location\":\"7.2905425, 80.5986581\",\"stopover\":true},{\"location\":\"7.300322, 80.386362\",\"stopover\":true}]"
Here's the structure of the code I use.
$(document).ready(function() {
$.ajax({
url: "aa.php",
type: "POST",
data: {
id: selected_i
},
success: function(result) {
itins = $.parseJSON(result);
$("#waypt_sel").val(JSON.stringify(itins.arr_intin));
}
});
$.ajax({
type: "POST",
contentType: "application/json",
url: "dd.php",
success: function(result) {
locations = $.parseJSON(result);
initializeMap();
}
});
function initializeMap() {
//other code
calculateAndDisplayRoute();
//other code
function calculateAndDisplayRoute() {
//other code
waypts_input = $.parseJSON($("#waypt_sel").val());
waypts_json_input = $.parseJSON(waypts_input);
//other code
}
}
});
And here is the detailed error message I get on firefox developer edition browser.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of
the JSON data
calculateAndDisplayRoute() map.js:366
initializeMap() map.js:290
.success() map.js:62
m.Callbacks/j() jquery-1.11.3.min.js:2
m.Callbacks/k.fireWith() jquery-1.11.3.min.js:2
x() jquery-1.11.3.min.js:5
.send/b() jquery-1.11.3.min.js:5
Thanks in advance.
"\" is unnecessary when deserialize json string in javascript .
what json tools you used?
you serialize in one tool , and deserialize with other , may get this scene .
The issue was that I was using an asynchronous ajax request to retrieve json data. by the time the data had been retrieved and pasted to the html, the execution of the code that used the html data had happened, and thus gave an error. I used a callback function for the ajax query and this did the job.
function get_det(callback) {//Your asynchronous request.
$.ajax({
url: "aa.php",
type: "POST",
success: function (result) {
alert("1st call");
callback();//invoke when get response
}
});
}
and in the code where this is called:
get_det(secondFunction);//calling with callback function
function secondFunction()//your callback function
{
alert("2nd Call");
}
Alternatively you may also try async: false in the ajax query parameters. But this can cause browser freezing and is not recommended.

Why getting NULL even JSON Array exist in response of jQuery.ajax?

Basically response consist of two things JSON Array and isValid(flag)
I can get flag value successful But it gives the null var resJSON = jQuery.parseJSON(data.notification);. I debug my script in chrome console but json response exist in data.
Might be following code and console result help you to understand my problem!
function getNotificationById(notificationId) {
jQuery.ajax({
type: "POST",
url: "<%=request.getContextPath()%>/GetNotifications/",
dataType : "json",
data: {"operation": "getNotificationById", "notificationId": notificationId},
success:function(data){
var resJSON = jQuery.parseJSON(data.notification);
// ^-- here is null
if (data.isValid) {
// ^-- response is true
jQuery.each(resJSON,function(i, value){
console.log(value.Body);
});
}
}
});
}
Chrome Console Result:
Edit
I have tried following solutions:
var resJSON = data.notification; // Chrome Console return **undefined**
You have a typo.
The data as shown in traces are included in data.notificaiton and not data.notification

JSON Request appended with [object%20Object] in jQuery

I'm trying to fetch a custom JSON feed I have written with jQuery using the getJSON method. For an unknown reason the URL seems to be having cache_gen.php?location=PL4 stripped from the end and replaced with [object%20Object] resulting in a 404 error occurring.
Here's the jQuery I'm using:
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
console.log(api_location + '?location=' + user_location);
jQuery.getJSON({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
From the console log I can see the URL string is calculated correctly as: http://weatherapp.dev/cache_gen.php?location=PL4
However the second line in the console is: Failed to load resource: the server responded with a status of 404 (Not Found).
Can anyone point me in the right direction with this?
UPDATE 19/01/2013 23:15
Well, I've just converted so that is fits the docs perfectly using $.ajax. I've also added a fail event and logged all of the data that gets passed to it.
var fetchData = function() {
if (Modernizr.localstorage) {
var api_location = "http://weatherapp.dev/cache_gen.php";
var user_location = "PL4";
var date = new Date();
var url = api_location + '?location=' + user_location;
console.log(url);
jQuery.ajax({
type: "GET",
url: api_location + '?location=' + user_location,
dataType: "json",
success: function(jsonData) {
console.log(jsonData);
},
error: function( jqXHR, textStatus, errorThrown ) {
console.log('textStatus: ' + textStatus );
console.log('errorThrown: ' + errorThrown );
console.log('jqXHR' + jqXHR);
}
});
} else {
alert('Your browser is not yet supported. Please upgrade to either Google Chrome or Safari.');
}
}
fetchData();
After this my console gives me the following information:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
I have ensured the headers for the JSON feed are current, and the feed is definitely serving valid JSON (it effectively caches a 3rd party service feed to save costs on the API).
The reason why you see this error:
http://weatherapp.dev/cache_gen.php?location=PL4
download_api.js:44textStatus: parsererror
download_api.js:45errorThrown: SyntaxError: JSON Parse error: Unable to parse JSON string
download_api.js:46jqXHR[object Object]
Is because your JSON is invalid. Even if a response comes back from the server correctly, if your dataType is 'json' and the returned response is not properly formatted JSON, jQuery will execute the error function parameter.
http://jsonlint.com is a really quick and easy way to verify the validity of your JSON string.
I was running into the same issue today. In my case I was assigning a JSON object to a variable named 'location' which is a reserved word in JavaScript under Windows and appearantly is a shorthand for windows.location! So the browser redirected to the current URL with [object%20Object] appended to it. Simple use a variable name other than 'location' if the same thing happens to you. Hope this helps someone.
Check out the actual function usage:
http://api.jquery.com/jQuery.getJSON/
You can't pass on object parameter into $.getJSON like with $.ajax, your code should look like this:
jQuery.getJSON('api_location + '?location=' + user_location)
.done(function() {
//success here
})
.fail(function() {
//fail here
});
To maybe make it a little clearer, $.getJSON is just a "wrapper function" that eventually calls $.ajax with {type:'get',dataType:'JSON'}. You can see this in the link I provided above.

Categories

Resources