I've got these two simple functions:
function getBatchSliceInfo(batch_num){
//get the batch slice info for the batch_num
alert('batch num is ' + batch_num); //returns the batch_num correctly
$.getJSON("statistics_batchdb.jsp", {batch_number: batch_num, slice_stats: 'true'}, showTable);
}
function showTable(data){
$("#table_slice_stats").hide();
if(data.error){
console.log("Something went wrong");
}
var jo = $.parseJSON(data);
alert('This JSON object has this many elements: ' + jo.length);
$.each(jo[0], function (i, val){
alert('This i value is' + i );
alert('This val value is' + val);
});
$("#table_slice_stats").show();
}
So I call getBatchSliceInfo on the click of a button and we get the JSON.
The response seems to be correct, so server side I'm alright.
However, I'm not passing that response correctly to showTable. "data" appears to be null because in the console I get the error:
Uncaught TypeError: Cannot read property 'length' of null batch_statistics_new.jsp:274
showTable batch_statistics_new.jsp:274
o jquery-1.7.2.min.js:2
p.fireWith jquery-1.7.2.min.js:2
w jquery-1.7.2.min.js:4
d jquery-1.7.2.min.js:4
I'm sure this is a very simple syntax question but I have no idea what's going on.
check your data
var data= [{slice_name:Nutrion,iteration_zero:.....},{......},{......}]
After convert to json Format.your data become like this,
var data= {[{slice_name:Nutrion,iteration_zero:.....},{......},{......}]} //It not json format.
if you tring to use length property it throwing an exceptions.so,do the same think without parsing into json.
Related
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
I'm trying to retrieve data from an API endpoint that i created with Django Rest Framework. At first, my code worked but now i keep getting this error:
Uncaught TypeError: Cannot read property 'ticker' of undefined
It's weird, because the console.logstatement in the following code returns nothing, although i'm sure that there is data in the endpoint that i'm calling.
This is what the data i'm trying to retrieve looks like:
[
{
ticker: "TEST",
Price: 7876
}
]
And this is the Ajax function that i built:
function doPoll(){
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
console.log(data[0]);
$('#data').text(data[0].ticker + ' ' + data[0].Price);
setTimeout(doPoll, 100);
});
}
doPoll();
And this is where the data should appear:
<h3 id="data"></h3>
The function should be supposed to place my data on my html page and refresh that data every second.
http://127.0.0.1:8000/tst/ is the DRF API endpoint that i'm trying to call, from where i'm retrieving the JSON data.
you need to access data.results... this is standard DRF response format
function doPoll(){
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
var results = data.results;
console.log(results[0]);
$('#data').text(results[0].ticker + ' ' + results[0].price);
setTimeout(doPoll, 100);
});
}
doPoll();
You have a typo here data[0].Price should be data[0].price
$.getJSON('http://127.0.0.1:8000/tst/', function(data) {
if(data && data.length > 0){
console.log(data[0]);
$('#data').text(data[0].ticker + ' ' + data[0].Price);
setTimeout(doPoll, 100);
}else{
//console.log('No Data')
console.log("DATA is: ", data)
}
});
Validate that data[0] exists before accessing properties of it
The best way to debug this is to check the response in your browser dev tools
Network tab
I have trouble with my script in PHP which get a json array.
I use the following code:
$(function() {
$("img").click(function() {
auswahl = $( this ).attr("id");
$.get('mail_filebrowser_add2.php?datenID=' + auswahl, function(data) {
alert("Server Returned: " + data.hello);
});
return false;
});
I expect the the alert show "Server Returned: abc".
Because the value of the key "hello" from the JSON Object is "abc".
But I get only the information "Server Returned: undefined".
If I run the script where the JSON query comes from it looks fine:
{"hello":"abc"}
Any idea what i do wrong?
You can use JSON.parse to parse the data into JSON object,
var parsedObject = JSON.parse(data);
and then use parsedObject.hello
I'm trying to parse the following JSON response:
{
"AgApplyTableE*!": [
{
"Index": 1,
"StringVal": "Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"
}
]
}
Here's my code:
$('#applyfailreason').click(function (){
var t = $(this);
var DeviceName = $('.DeviceName').val();
var Username = $('.Username').val();
var Password = $('.Password').val();
$.ajax({
method: 'GET',
url: 'http://' + DeviceName + '/config/AgApplyTable',
headers: {
"Authorization": "Basic " + btoa('' + Username + '' + ":" + '' + Password + '')
},
dataType: 'json',
contentType: 'application/json',
success: function(data) {
var test = JSON.stringify(data);
console.log(test);
},
statusCode: {
406 : function() {
alert('There is an unexpected string in your data.\nFix the error and try again.');
},
401 : function() {
alert('Wrong username or password.');
}
},
});
});
I get the following on the console (which is ok):
{"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]}
But I want to print only the "StringVal" out of the JSON response.
Tried:
var test2 = JSON.stringify(data.StringVal);
console.log(test2);
Gives:
undefined
I also tried the following (with dataType: 'jsonp',):
var test4 = JSON.parse(data.StringVal);
But then Chrome sends a GET request to a strange URI (which actually gives 200OK):
config/AgApplyTable?callback=jQuery111306132095118518919_1436256387242&_=1436256387244
And I get the following error:
Uncaught SyntaxError: Unexpected token :
Any idea how to print to console only "StringVal" out of the JSON response?
Thanks.
Your response is an object containing one property named "AgApplyTableE*!", which is an array that contains one element, which is an object that contains the property "StringVal".
So you'd have to access it by data["AgApplyTableE*!"][0].StringVal.
Use console.log(data['AgApplyTableE*!'][0].StringVal)
In your response, there is no such thing as StringVal as direct suboridnate of data. The property StringVal is inside the internal object AgApplyTableE*! therefore data.StringVal is undefined.
Also, another problem I see here is that you're stringifying the response and then trying to access the property StringVal.
If you stringify, you test variable will be a string and string doesnt have a property StringVal (unless you set that in your proto)
EDIT:
Added missing [0] index.
Try
var test2 = data["AgApplyTableE*!"][0].StringVal;
console.log(test2);
test ={"AgApplyTableE*!":[{"Index":1,"StringVal":"Error: Enabled virtual server 3 has no IP address.U+0085Error: Apply not done. Use 'diff' to see pending changes,U+0085 then use configuration menus to correct errors.U+0085"}]};
console.log(test["AgApplyTableE*!"][0]["StringVal"]);
Demo
I think that is because you have two levels here, not only one. In order to get that value out, you probably would need something like
var test2 = JSON.parse(data);
console.log(test2["AgApplyTableE*!"][0].StringVal);
Altough I'm not sure AgApplyTableE*! is a really good identifier here. Probably you can change something else, and then you can also use . notation to reach the members.
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.