Search code examples
jqueryajaxopenweathermap

Not able to get data from openweatherapi


I am trying to create a simple Weather APP and I am using the jquery Ajax method to retrieve the data from openweathermap. I am using the following method to get the data.

$(document).ready(function(){
$('#submitWeather').click(function(){
let city = $("#city").val();
if(city != ''){
  //Get the AJAX request.
  $.ajax({
    url:'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&appid=b1b15e88fa797225412429c1c50c122a1",
    type: "GET",
    //jsonpadded.
    dataType: "jsonp",
    //the callback for success.
    success: function(data){
      console.log(data);
    }
  });
}else {
  $("#error").html('Field cannot be empty');
}
 });
 });

The problem I am having is that it is not getting the data showing it in the console.log. This is the error I am getting in the console.log

jquery.min.js:4 GET http://api.openweathermap.org/data/2.5/weather?q=London&appid=b1b15e88fa797225412429c1c50c122a1&callback=jQuery31106677768465103353_1512307813960&_=1512307813961 net::ERR_ABORTED
send @ jquery.min.js:4
ajax @ jquery.min.js:4
(anonymous) @ app.js:6
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3

Solution

  • the dataType of ajax request is "json" not "jsonp"

    dataType (default: Intelligent Guess (xml, json, script, or html))

    ref: http://api.jquery.com/jquery.ajax/

    $.ajax({
        url:'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&appid=b1b15e88fa797225412429c1c50c122a1",
        type: "GET",
        dataType: "json",
        success: function(data){
          console.log(data);
        }
      });
    

    UPDATE:

    openweathermap supports "JSONP" but you are using it wrongly here is an example of how to use it with $.ajax to call a named method

    function callback(data){
        console.log(data);
    }
    
    $.ajax({
        url:'http://api.openweathermap.org/data/2.5/weather?q=' + city + "&appid=b1b15e88fa797225412429c1c50c122a1",
        type: "GET",
        dataType: "jsonp",
            jsonp : "callback",
            jsonpCallback: "callback"
            });