4

I'm accessing a dictionary REST API using Ajax.

$.ajax({
  url: "http://api.wordnik.com//v4/word.json/cat/definitions?api_key=mykey&includeRelated=false&includeTags=false&limit=1",
  dataType : 'json',
  success: function(data) {
    //called when successful
    alert(data.word);
  },
  error: function(e) {
    //called when there is an error
    console.log(e.message);
  }
});

The response:

[
  {
    "textProns": [],
    "sourceDictionary": "ahd-legacy",
    "exampleUses": [],
    "relatedWords": [],
    "labels": [],
    "citations": [],
    "word": "cat",
    "text": "A small carnivorous mammal (Felis catus or F. domesticus) domesticated since early times as a catcher of rats and mice and as a pet and existing in several distinctive breeds and varieties.",
    "sequence": "0",
    "score": 0.0,
    "partOfSpeech": "noun",
    "attributionText": "from The American Heritage® Dictionary of the English Language, 4th Edition"
  }
]

In my test example I get an alert undefined on success. Most Ajax examples I saw use loops but I'm returning one result. How can I extract the word and text values from the objects?

dda
  • 6,030
  • 2
  • 25
  • 34
CyberJunkie
  • 21,596
  • 59
  • 148
  • 215

3 Answers3

7

As you can see your response starts with [ and ends with ]. So your response is an array. Then, inside the array, you get objects (starting with { and ending with }). So your data is an array, which can be accessed with data[x] (x being the index), and each member of the selected object can be accessed with the .dot notation: .word, .text etc. So in your case, if there's only one result, you can do data[0].word.

dda
  • 6,030
  • 2
  • 25
  • 34
6

The response is an object inside of an array. Try data[0].word

sachleen
  • 30,730
  • 8
  • 78
  • 73
3

You want to change the success function like this,

success: function(data) {
  alert(data[0].word);
}

I verified the value coming correctly.

jQuery AJAX

dda
  • 6,030
  • 2
  • 25
  • 34
Jayamurugan
  • 1,757
  • 2
  • 14
  • 34