I want to display a name from this url http://api.open-notify.org/astros.json/
Here is my code,
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.results[0].formatted_name;
console.log('Name : ', name);
});
I want to display it with my h3 tag. I'm new to JSON and jQuery. I keep getting
index.html:631 Uncaught TypeError: Cannot read property '0' of undefined error
You have to use the success() or done() function.
var url = "http://api.open-notify.org/astros.json/";
$.getJSON(url).success(function (json) {
var name = json.people[0].name
console.log('Name : ', name)
})
If you are able to reach out to the specific endpoint and not be blocked by CORS it must be the format of the data.
Looking at the data, there is no property called results in your data. Try debugging that line to see the proper format of the variable json. It may be a string and you would need to call JSON.parse(json); in order to format it properly as an object.
You should be able to do:
var astrosAPI = "http://api.open-notify.org/astros.json/";
$.getJSON(astrosAPI, function (json) {
var name = json.people[0].name;
console.log('Name : ', name);
});
Related
In one of my web pages I am making an AJAX call to retrieve a member's profile properties so that they can make changes. The code being used to do this is as so:
function loadProfileData() {
var request = $.ajax({
url: "../handlers/getprofile.ashx",
method: "POST"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#spnProfileErr').html(msg.Status);
$('#toastProfileFail').toast('show');
}
else {
$('#lastname').val(msg.MemberProfile.LastName); // textbox
$('#firstname').val(msg.MemberProfile.FirstName); // textbox
$('#bestemail').val(msg.MemberProfile.BestContactEmail); // textbox
$('#agerange').val(msg.MemberProfile.AgeRange); // select control
$('#zipcode').val(msg.MemberProfile.ZIPCode); // textbox
}
});
request.fail(function (jqXHR, textStatus) {
$('#spnProfileErr').html('Unable to retrieve your existing profile at this time.');
$('#toastProfileFail').toast('show');
});
}
The call to the web service works just fine, and it returns a JSON String, as follows:
I can access the 'Success' and 'Status' properties of the returned JSON, but when I try to access the member profile properties of the MemberProfile in the JSON, it doesn't let me. For example, accessing msg.MemberProfile.LastName throws an undefined error.
What am I not doing right?
Probably, you're receiving just a string, try use
var msg = JSON.parse(msg)
at beginning of your callback, so it will convert your string to a desired object, try out
Try adding the type:"json" property inside the ajax object, just after the method property
I use Javascript to retrieve through a JSON api call the amount of active products pasted in a certain filter.
My typicall response would be
{"total":34,"product_ids":["PRODUCT1","PRODUCT2",....."]}
My script is working fine when products are present but when none of the products are active the response will be:
{"error":"No products found, please check request settings"}
In this case the script will crash.
What I tried to do is to set the var NumEdPicks to 0 when I get an error but I don't really know how as the script is crashing when it doesn't find "total".
This is what the retrieve part of the script looks like
// Retrieve
var url = 'http://api.jetlore.com/products/products_by_filter.json?jl_cid=' + clientID + '&filter=' + filterName + '&per_page=' + maxCount + '&page=1';
var response = HTTP.Get(url);
var responseObj = Platform.Function.ParseJSON(response["Content"]);
var NumEditorsPick = responseObj.total;
if(NumEditorsPick>maxCount){ var NumEditorsPick = maxCount;}
I would like to set NumEditorsPick to 0 when I get the error response.
Some things I was thinking about but which isn't working:
var NumEditorsPick = responseObj.total || 0
or
var NumEditorsPick = ‘total’ in responseObj ? responseObj.total : 0
How to define NumEditorsPick when there is no total?
I've tried so far:
if (responseObj.hasOwnProperty('total')){
var NumEditorsPick = responseObj.total;
}else{
var NumEditorsPick = 0;
}
And
if (responseObj.has("total")){var NumEditorsPick = responseObj.total;
}
if (responseObj.has("error")){var NumEditorsPick = 0;
}
Both are crashing the execution of my script, so I'm starting to think that when there is an error response it just stops the script and ignores the rest, would that be possible? In that case, how to ignore this error response?
EDIT:
After using the try/catch method as suggested in the comments, I managed to finally make it work:
var NumEditorsPick;
try {
var response = HTTP.Get(url);
var responseObj = Platform.Function.ParseJSON(response["Content"]);
NumEditorsPick = responseObj.total;
} catch (error) {
NumEditorsPick = 0;
}
You can use Javascript's hasOwnProperty() to check if the parse JSON has the key you're looking for.
In this case, I'd be something like:
var responseObj = Platform.Function.ParseJSON(response["Content"]);
if (responseObj.hasOwnProperty('error')){
// handle error msg
}else{
// do something else
}
Here's a simple example using the JSON input you've provided.
Update
Ok, so my initial answer was based on what you said here:
My script is working fine when products are present but when none of
the products are active the response will be:
{"error":"No products found, please check request settings"}
But the service you're calling does not return a JSON string containing the error. Instead it returns a 404 and therefore, any attempt to parse or use the response content is not valid.
So, to start, you could try wrapping your HTTP.Get(url)in a try/catch method and on the catch clause set the NumEdPicks to zero.
Another option would be to check HTTP.Get() method documentation to see if the response object has a status (e.g: response.Status) or if you can pass a callback function for response and error, like this example in AJAX:
$.ajax({
url: 'yourUrl',
type: 'GET',
success: function(data){
// Set NumEdPicks to total and do other stuff
},
error: function(data) {
// Set NumEdPicks to zero
}
});
I have the following JSON data from my API
[{"email":"user#gmail.com","status":"Active"}]
This is the JS/jQuery code I am using to get the data
function formLogin() {
var email = document.getElementById("email").value;
var password = document.getElementById("password").value;
var dataString = "email=" + email + "&password=" + password;
jQuery.ajax({
url: "http://localhost/OnlineShop/API/fetch_user_login_api.php",
data: dataString,
type: "POST",
success: function(data) {
$("#login-form").html(data);
console.log('success');
//window.location.href = "store.html?shopper=";
var obj = jQuery.parseJSON(data);
alert(obj.email);
},
error: function() {
console.log('error');
}
});
return true;
}
alert(obj.email) is throwing undefined. How do I retrieve the email and status from the JSON result?
Your "data" variable is already an object or an array, you don't need to call parseJSON.
Then, it seems that your object is an Array of objects
This should work:
alert(data[0].email);
I advice you to check if your array is empty or not before calling this line.
The API returns [{"email":"user#gmail.com","status":"Active"}] as it is of type Array.
first you need to take the first element of the Array by obj = obj[0].
then it is something like {"email":"user#gmail.com","status":"Active"}.
now you can get the email element by simply obj["email"]
if you call your api and get the result like this:
[{"email":"user#gmail.com","status":"Active"}]
it's an array, what you can do to fix the error is:
1) change your api response structure to JSON not array
2) use for to iterate your response
And I advice you next time, you have this kind of error, just console.log the raw data to find what's the structure of it, and you'll have the solution.
I get a JSON from my response object so I do:
var json = JSON.parse(res.text);
I print the JSON and get JSON back. But when I retrieve the value inside json.body.value.total then it gives this error:
Uncaught TypeError: Cannot read property 'total' of undefined
I have no idea why. I pasted the value that receive from var json and printed on console and was able to retrieve total. But I cannot do it through the code. There is a JSON value total. Its just unable to recognize. On the console, it works but does not work in the code.
I get JSON back from my response object which I retrieve using response.text. I think it needs to change in parsable object but all it returns is undefined
it('returns http 200', function (done) {
chai
.request(baseUrl)
.get('/api/')
.set('Authorization', 'Basic abc')
.query({val:'hey'})
.end(function(err, res) {
expect(res).to.have.status(200);
var json = res.text;
console.log('val: '+ JSON.parse(json.body));
var val = json.body.value.total; //undefined
expect(val.to.be.above(0)); //fails
done();
});
});
The REST API that I built was returning the response.body but what worked is this:
var body = JSON.parse(json.body);
var obj = JSON.stringify(body);
var jsonObj = JSON.parse(obj);
The above looks ridiculous but thats what worked. json -> object -> json. It was finding trouble to figure out that its a json object.
The console was doing a good job but not the library that I was using.
The complete code is this:
it('returns http 200', function (done) {
chai
.request(baseUrl)
.get('/api/')
.set('Authorization', 'Basic abc')
.query({val:'hey'})
.end(function(err, res) {
expect(res).to.have.status(200);
var json = res.text;
var body = JSON.parse(json.body);
var obj = JSON.stringify(body);
var jsonObj = JSON.parse(obj);
var val = jsonObj.body.value.total;
expect(val.to.be.above(0));
done();
});
});
You're not assigning the parsed value to json.
var json = res.text;
should be
var json = JSON.parse(res.text);
You have to put you json string into JSON.Parse() and access the properties on the result of the Parse function.
You can't just access properties from a text.
I have this code:
function parseContent(targetDiv) {
$("#"+targetDiv+" > [contentName]").each(function (index) {
var data = $(this).attr("contentData");
if(data != undefined) {
alert(data);
alert(jQuery.param(data));
}
})
}
It parses some html and looks for elements with contentName as an attribute in them. For each of those, check to see if there is an attribute contentData, and if so turn the json into parameters.
It's doing the each() just fine. However I get one alert (the first one) prints:
{reportId : 5}
which is correct, but then fails and in the console i get:
TypeError: this.replace is not a function
Im pretty sure that is correct JSON format. I have tried it with adding quotes also like {'reportId':5} but I get the same error;
Any Ideas?
It's because $.param expects a JSON Object as its parameter and not a string formatted as JSON. So if you pass something like this, it's going to fail:
var jsonElement = '{"reportId": 5}';
var result = $.param(jsonElement); //throws exception
Instead, if you do:
var jsonElement = '{"reportId": 5}';
var result = $.param(JSON.parse(jsonElement));