WHY! Why is this not working. I am using the weatherbit api, and trying to simply get the uv index. Mind you, in a browser the proper link displays all the information but I can not get it to work through js, putting it through to a div.
I replaced the actual request data with (nameOfData) for privacy, I assure you that there is no problem with the parameters specific.
$getJSON('https://api.weatherbit.io/v2.0/current?lat=(Lat)&lon=(Lon)&key=(Key)', function(data) {
// JSON result in `data` variable
$(".UV").html(data.data[1].uv);
});
Please help.
It is failing because you need an API key. Using the URL in the address bar of a browser does not have that restriction.
Sometimes a workaround in this case is to use a proxy on a server. Your code queries the server, and the server mimics a browser. It depends on the web service how you will fare.
I got it working with async, somehow.
async function getData(){
let response = await fetch(weatherbitApi);
let data = await response.json()
return data;
}
getData().then (data =>
console.log(data.data[0]));
Related
I am using AJAX call in JS and calling a controller and action method with the url
I ran the code in my local it is working fine but when it was deployed in production the AJAX call didn't get the data and it is throwing a message in console
Could not load content for https://az416426.vo.msecnd.net/scripts/JavaScript/JavaScriptSDK/ajax/ajax.ts (HTTP error: status code 404, net::ERR_HTTP_RESPONSE_CODE_FAILURE)
The data on local is limited but it has more data on production
I tried it by calling through AJAX and from the action method I am returning the data in the JSON format and the data i recieved is parsed and then it is sent to a hidden field it was running fine on my local all the data is there but when it was deployed on production after the page load the ajax will be called but I can't able to see the data and it shows the error which I mentioned above.
I will give you two recommendations that work better for me when dealing with passing JSON data from a controller.
First try this on your get data method:
[HttpGet]
public ContentResult Getsubscriptiondata()
{
var subdata = db.ExistingSubscriptionList.Where(substatus => substatus.OSCP_SubStatusId == "1").ToList();
return Content(JsonConvert.SerializeObject(subdata));
}
Second in your javascript change the line
document.getElementById('hdnExistingSubs').value = JSON.stringify(data)
to
document.getElementById('hdnExistingSubs').value = JSON.parse(data)
This gives me more consistent results when receiving data from the controller, hope this helps.
Clarification: I prefer this methods because passing a Json result sometimes haves quirks in the way the data is rendered on the javascript in the browser.
There is a handy IP tracker at https://ipapi.co/json/. I want viewers of my website to see their IP address at the bottom of the webpage. What I have right now is:
<div class="container">
<div id="IP">IP Address should show here.</div>
<script>
document.getElementById('IP').innerHTML = (https://ipapi.co/json/).ip;
</script>
</div>
However, this doesn't display the IP address. I'm probably using the wrong approach. How do I get it to display correctly?
Edit:
I tried doing:
<div class="container">
<div id="IP">IP Address should show here.</div>
<script>
fetch('https://ipapi.co/json/')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
document.getElementById('IP').innerHTML = JSON.stringify(myJson.ip);
});
</script>
</div>
But that isn't working either.
You might consider using javascript Fetch API.
In your case it could be something like this:
fetch('https://ipapi.co/json/')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
document.getElementById('IP').innerHTML = JSON.stringify(myJson.ip);
});
The keyword you are looking for is AJAX.
AJAX are requests in the background with which you can load more data. However, for security reasons this is not possible for cross-domain. Your only option is to create your own interface in your own backend that provides you with the JSON data.
PS: Your question has been voted down because it seems you haven't even looked for a solution on the internet.
What you are after is something like this:
<div>IP address: <span id="ipfield">loading...</span></div>
<script>
function callback(json) {
document.getElementById("ipfield").innerHTML = json.ip;
}
</script>
<script src="https://ipapi.co/jsonp/"></script>
Note that the format parameter in the URL for IP API has been changed from json to jsonp. JSONP format is just like JSON, but with a javascript function wrapped around it. When you load a JSONP file as the source for a script, it calls the callback function, passing the JSON data as an argument.
This only works because the site you are using provides the data in JSONP format as well as pure JSON. If it didn't, you would need to use one of the more complicated solutions given in the other answers.
You can't just get the data/json from the website by inserting a URL in brackets.
Consider reading something about HTTP requests, fetching data, about JSON, and JSON methods: parse() and stringify(), to avoid having similar problems in the future.
https://medium.com/#sahilkkrazy/fetch-vs-axios-http-request-c9afa43f804e
What is difference between Axios and Fetch?
Difference between JSON.stringify and JSON.parse
And there is your example of solution:
fetch("https://ipapi.co/json/")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
const ip = myJson.ip;
document.getElementById("IP").innerHTML = ip;
});
Codesandbox:
https://codesandbox.io/s/9ql9zr2o14
I am trying to make an API call to Openweathermap using their API+key. I am unable to parse the data to a CSS ID using $.getJSON in Javascript.
This is the jsfiddle: https://jsfiddle.net/n1Lz3vf0/
Code:
var weatherData = "http://api.openweathermap.org/data/2.5/weather?
q=Endicott,us&appid=API+KEY";
$.getJSON(weatherData, function(data){
var town = data.name;
document.getElementById('town').innerHTML = town;
});
And it outputs to a simple div tag
Obviously the end result will be far more involved and I will be parsing much more data, but in the jsfiddle, it should simply output my city name but it's not.
You have a mixed content error on the jsfiddle page, because it's a https website and you're trying to call a http url in your API call. You can't call an external API using http if you're over https, the request is blocked.
I tried your request with https and it works just as expected.
I did some research on retrieving cross domain JSON data, but when I implemented it, the code didn't work. Doing some more research, I found that browsers don't let websites retrieve data from a different host due to security reasons. I found an answer that said I should use JSONP, but it still wasn't working? This was my code.
function getWeather(location){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?q=" + location + "&appid=/*my usual app id is here*/&callback=?", function(result){
//response data are now in the result variable
alert(result.weather[0].description);
var changeW = document.getElementById("theweathertext");
changeW.innerHTML = "The current weather at your destination: " + result.weather[0].description +".";
});
}
When I test the code, the browser isn't letting me retrieve the data? How would I fix this? Thanks in advance.
UPDATE: This code was working when I was testing it locally, but when I did a live launch preview, it didn't work. Could this be some other problem?
I think this code will work if you provide a valid apikey:
$.getJSON(
'http://api.openweathermap.org/data/2.5/weather?q=lisbon&callback=?',
function(data){
console.log(data);
}
);
EDIT: It currently gives me 401 code which means i have no rights to access this endpoint. That is why i'm suggesting to use a valid api key.
I am trying to read the finance info from the google page into a json object.
Code is below:
try {
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?",function(data){
alert(data);//var jsondata = data;
//jsonobj = $.parseJSON(jsondata);
//alert(jsonobj[0].id);
});
} catch(e) {
alert(e.toString());
}
However I keep getting this error all the time on firebug
invalid label
"id": "4052464"
Is there any way this info can be read. My ultimate goal is to create a windows 7 gadget that doesnt use server side scripting and can be used from any Windows 7 system.
Appreciate all the help.
John
Response isn't valid JSON (response is prefixed with //), so jQuery won't be able to parse it correctly anyway.
To solve change &jsoncallback=? to &callback=?
so
$.getJSON("http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&callback=?", function(data) {
alert(data)
});
The response from Google has two leading /'s, making the response invalid JSON... for some reason.
Because of this, you cannot use jQuery.getJSON, as it expects a JSON response. Instead, you should use jQuery.get, and parse the JSON yourself after removing the two leading slashes.
jQuery.get('http://finance.google.com/finance/info?client=ig&q=NSE:GOLDBEES&jsoncallback=?', function (string) {
var validJson = string.slice(2);
var obj = jQuery.parseJSON(validJSON);
// use obj
});
Two additional points:
No JSONP is being used, so you don't need the jsoncallback=? in your request URL
The Windows Sidebar has been retired, so you cannot publish you finished gadget to the official gallery.