Parsing ajax JSON response in a loop - javascript

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

Related

JSON syntax error in firefox only

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

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

Node.js and Express - Sending JSON object from SoundCloud API to the front-end makes it a string

I have been using an http.get() to make calls to the SounbdCloud API method to receive a JSON object that I would like to pass to the browser. I can confirm that the data I receive is an object, since I the typeof() method I call on the data prints out that it is an object.
var getTracks = http.get("http://api.soundcloud.com/tracks.json?q="+query+"&client_id=CLIENT_ID", function(tracks) {
tracks.on('data', function (chunk) {
console.log(typeof(chunk)); // where I determine that I receive an object
res.send(chunk);
});
//console.log(tracks.data);
}).on("error", function(e){
console.log("Got error: "+e);
});
But when I check the data I receive in the AJAX request I make in the browser, I find that the data received has a type of String (again, I know this by calling typeof())
$('#search').click(function(e){
e.preventDefault();
var q = $("#query").val();
$.ajax({
url: '/search',
type: 'POST',
data: {
"query": q
},
success: function(data){
alert(typeof(data));
alert(data);
},
error: function(xhr, textStatus, err){
alert(err);
}
})
});
I would appreciate the help, since I do not know where the problem is, or whether I am looking for the answer in the wrong places (perhaps it has something to do with my usage of SoundCloud's HTTP API)
JSON is a string. I assume you need an Object representing your JSON string.
Simply use the following method.
var obj = JSON.parse(data);
Another example would be:
var jsonStr = '{"name":"joe","age":"22","isRobot":"false"}';
var jsonObj = JSON.parse(jsonStr);
jsonObj.name //joe
jsonObj.age // 22

what does Uncaught SyntaxError: Unexpected token < mean?

For this line of code :
var result = eval('('+result+')');
In this context:
function saveUser(){
alert(url);
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
var result = eval('('+result+')');
if (result.errorMsg){
$.messager.show({
title: 'Error',
msg: result.errorMsg
});
} else {
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
}
}
});
}
How do i fix the error?
what does Uncaught SyntaxError ... mean?
It means that eval cannot parse the input (as JavaScript) because it contains a < where there shouldn't be one. FWIW if the response is HTML, JSON.parse wouldn't help either.
How do i fix the error?
You either have to treat the response how it is expected to be treated, e.g. don't pass it through eval if it's HTML.
Or you fix the server side and return the repsonse that the client side expects, e.g. JSON.

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