Reputation: 1
I'm trying to work on a simple Ajax call and I'm unable to figure out what's gone wrong. The ajax call is successful but nothing is alerting. When I console.log(myStats), it displays the JSON in my console though.
var main = function(){
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0',
success: function(data) {
var myStats = JSON.parse(data);
alert(myStats);
},
error: function(){
alert('error');
}
});
};
$(document).ready(main);
Upvotes: 0
Views: 7363
Reputation: 22959
You don't need to parse the response as it's already a JSON. Though ajax should automatically know this, just to be sure you can set dataType
explicitly. Also, you can't really alert()
a json object.
var main = function() {
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0',
dataType: 'json',
success: function(data) {
console.log(data);
// do things with data here.. this for instance
var html = jsonToHtml(data);
$('#output tbody').html(html);
},
error: function() {
alert('error');
}
});
};
function jsonToHtml(data) {
var html = '';
$.each(data, function(k, v) {
if (typeof v === 'object') {
html += jsonToHtml(v)
} else {
html += "<tr><td>" + k + "</td><td>" + v + "</td></tr>";
}
});
return html;
}
$(document).ready(main);
table {
width: 100%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 4px 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<table id="output">
<thead>
<tr>
<th>KEY</th>
<th>VALUE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Upvotes: 1
Reputation: 2130
function main(){
$.ajax({
type: 'GET',
url: 'http://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=2de143494c0b295cca9337e1e96b00e0',
}).done(function(data){
console.log(data)
})
};
$(document).ready(main);
Instead of success call back, use Deferred object.
for success use .done().
this works.
Upvotes: 0