1

I am trying to load a remote json file asynchronously. I've just spent a long time trying to debug the function that I expected to work. I'm still relatively new to JS, and would like to understand why teh following occurs.

The function I expected to work returns undefined.

$.ajax({
  dataType: 'json',
  url: $url
})
.done(function(data) {
  console.log( data );
});

Whereas this function returns the expected json object

$.getJSON( $url, function( data ) {
  console.log(data);
});

I thought these functions are equivalent. What is happening here?

Andy Harvey
  • 12,333
  • 17
  • 93
  • 185

2 Answers2

0

You are setting a wrong attribute in the ajax method. type is meant to be GET, POST, etc. but you are setting it up to json.

"type is an alias for method. You should use type if you're using versions of jQuery prior to 1.9.0."

For that to be correct, you need to set the dataType to 'json' and everything should fall in place. You can read more about ajax API on jQuery Docs site

Sreekanth
  • 3,110
  • 10
  • 22
0

try this instead

$.ajax({
  dataType: 'json',
  url: $url,
  success: function(data)
  {
    console.log( data );
  }
})